Linux socket通訊(TCP)
阿新 • • 發佈:2018-12-31
服務端
#include<stdio.h> #include <sys/socket.h> #include<string.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #define TCP_PORT 9999 int main() { char ipbuf[32]; char recbuf[0x1000]; int socket_ser,socket_accept; socket_ser = socket(AF_INET,SOCK_STREAM,0); struct sockaddr_in addr,addr_c; bzero(&addr,sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(TCP_PORT); addr.sin_addr.s_addr = htonl(INADDR_ANY); bind(socket_ser,(struct sockaddr *)&addr,sizeof(addr)); listen(socket_ser,128); while(1) { bzero(ipbuf, sizeof(ipbuf)); bzero(&addr_c,sizeof(addr_c)); bzero(recbuf,sizeof(recbuf)); int len_c; socket_accept = accept(socket_ser,(struct sockaddr *)&addr_c,(socklen_t *)&len_c); inet_ntop(AF_INET,&addr_c.sin_addr.s_addr,ipbuf,sizeof(ipbuf)); printf("Ip is %s,port is %d\n",ipbuf,ntohs(addr_c.sin_port)); int len = read(socket_accept,recbuf,sizeof(recbuf)); printf("%s\n",recbuf); write(socket_accept,recbuf,len); close(socket_accept); } close(socket_ser); return 0; }
客戶端
#include<stdio.h> #include <sys/socket.h> #include<string.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #define TCP_PORT 9999 int main() { int socket_fd,socket_accept; socket_fd = socket(AF_INET,SOCK_STREAM,0); struct sockaddr_in addr; bzero(&addr,sizeof(addr)); addr.sin_family = AF_INET; addr.sin_port = htons(TCP_PORT); inet_pton(AF_INET,"127.0.0.1",&addr.sin_addr.s_addr); connect(socket_fd,(struct sockaddr*)&addr,sizeof(addr)); char bufsend[] = "hello world"; char bufrec[0x1000]; bzero(bufrec,sizeof(bufrec)); write(socket_fd,bufsend,strlen(bufsend)); read(socket_fd,bufrec,sizeof(bufrec)); printf("%s\n",bufrec); close(socket_fd); return 0; }
沒啥知識點,需要注意的是socket_accept即是三次握手完成,用inet_ntop轉換ip要好點 inet_ntop是可重入函式