socket客户端代码实现
相关函数
(1)socket()函数
int socket(int domain, int type, int protocol);
(2)bind()函数: IP号端口号与相应描述字赋值函数
int bind(int sockfd, const struct sockaddr *addr,socklen t addrlen);
(3)listen()函数:监听设置函数
int listen(int sockfd, int backlog);
(4)accept()函数
int accept(int sockfd, struct sockaddr *addr, socklen t *addrlen);
服务端代码实现:
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main() { int s_fd; int n_read; char readBuf[128]; char *msg = "I get your connect"; struct sockaddr_in s_addr; struct sockaddr_in c_addr; memset(&s_addr,0,sizeof(struct sockaddr_in)); memset(&c_addr,0,sizeof(struct sockaddr_in)); //1.socket s_fd = socket(AF_INET,SOCK_STREAM,0); if(s_fd == -1) { perror("socket"); exit(-1); } s_addr.sin_family = AF_INET; s_addr.sin_port = htons(8989); inet_aton("10.100.13.165",&s_addr.sin_addr); //2.bind bind(s_fd,(struct sockaddr *)&s_addr,sizeof(struct sockaddr_in)); //3.listen listen(s_fd,10); //4.accept int clen = sizeof(struct sockaddr_in); int c_fd = accept(s_fd,(struct sockaddr *)&c_addr,&clen); if(c_fd == -1) { perror("accept"); } printf("get connect:%s\n",inet_ntoa(c_addr.sin_addr)); //5.read n_read = read(c_fd,readBuf,128); if(n_read == -1) { perror("read"); } else { printf("get message:%d,%s\n",n_read,readBuf); } //6.write write(c_fd,msg,strlen(msg)); return 0; }
客户端代码实现:
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main() { int c_fd; int n_read; char readBuf[128]; char *msg = "msg form client"; struct sockaddr_in c_addr; memset(&c_addr,0,sizeof(struct sockaddr_in)); //1.socket c_fd = socket(AF_INET,SOCK_STREAM,0); if(c_fd == -1) { perror("socket"); exit(-1); } c_addr.sin_family = AF_INET; c_addr.sin_port = htons(8989); inet_aton("10.100.13.165",&c_addr.sin_addr); //2.connect if(connect(c_fd,(struct sockaddr *)&c_addr,sizeof(struct sockaddr)) == -1) { perror("connect"); exit(-1); } //3.send write(c_fd,msg,strlen(msg)); //4.read n_read = read(c_fd,readBuf,128); if(n_read == -1) { perror("read"); } else { printf("get message from server:%d,%s\n",n_read,readBuf); } return 0; }
编译结果: