网络编程"/>
8.9 网络编程
tcp服务器搭建:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>#define PORT 8888
#define IP "192.168.31.98"#define MSG(msg) do{\fprintf(stderr,"__%d__",__LINE__);\perror(msg);\
}while(0)int main(int argc, const char *argv[])
{int pp = socket(AF_INET, SOCK_STREAM ,0);if(pp<0){MSG("socket");return -1;}printf("create socket success\n");struct sockaddr_in sin;sin.sin_family = AF_INET;sin.sin_port = htons(PORT);sin.sin_addr.s_addr = inet_addr(IP);if(bind(pp,(struct sockaddr*)&sin,sizeof(sin))<0){MSG("bind");return -1;}printf("bind success\n");if(listen(pp,10)<0){MSG("listen");return -1;}printf("listen success\n");struct sockaddr_in cin;socklen_t addrlen = sizeof(cin);int newfd = accept(pp,(struct sockaddr *)&cin,&addrlen);if(newfd<0){MSG("accept");return -1;}printf("%s : %d newfd = %d\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);char buf[128] = "";ssize_t res = 0;while(1){bzero(buf,sizeof(buf));res = recv(newfd,buf,sizeof(buf),0);if(res<0){MSG("recv");return -1;}else if(res == 0){printf("%s %d newfd = %d客户端退出\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);break;}printf("%s %d newfd = %d : %s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd,buf);}close(pp);close(newfd);return 0;
}
更多推荐
8.9 网络编程
发布评论