日期:2014-05-16 浏览次数:20894 次
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <unistd.h>/*定义close()*/ #include <sys/types.h>/*数据类型定义*/ #include <sys/socket.h>/*提供socket函数结构*/ #include <netinet/in.h>/*定义数据结构sockaddr_in*/ #include <arpa/inet.h>/*提供IP地址转换函数*/ #include <netdb.h>/*提供设置获取域名的函数*/ #define BACKLOG 1 #define PORT 2234 int main(int argc,char *argv[]) { int socketfd,connectfd; struct sockaddr_in server; struct sockaddr_in client; socklen_t sin_size; if((socketfd=socket(AF_INET,SOCK_STREAM,0))==-1) { perror("creat socketfd failed!"); exit(1); } int opt=SO_REUSEADDR; setsockopt(socketfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt)); bzero(&server,sizeof(server)); server.sin_family=AF_INET; server.sin_port=htons(PORT); server.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(socketfd,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1); { perror("bind error!"); exit(1); } if((listen(socketfd,BACKLOG))==-1) { perror("listen failed!"); exit(1); } sin_size=sizeof(struct sockaddr_in); if((connectfd=accept(socketfd,(struct sockaddr *)&client,&sin_size))==-1) { perror("accept failed!"); exit(1); } printf("you got a connection from%s:\n",inet_ntoa(client.sin_addr)); send(connectfd,"connect to server\n",20,0); close(connectfd); close(socketfd); return 0; }