sock服务端代码实现读写
前几章有具体介绍这几个函数,这里就简单罗列出来了
(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);
地址转换API
int inet_aton(const char* straddrstruct in_addr *addrp); 把字符串形式的“192.168.1.123”转为网络能识别的格式
char* inet_ntoa(struct in_addr inaddr); 把网络格式的ip地址转为字符串形式
#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; }
编译结果: