socket API

IPv4套接口地址结构

struct sockaddr_in {

uint8_t  sin_len;4

sa_family_t  sin_family;4

in_port_tsin_port;2

struct in_addrsin_addr;4

char sin_zero[8];8

};

通用地址结构

struct sockaddr {

uint8_t  sin_len;

sa_family_t  sin_family;

char sa_data[14];//14

};




服务端

//查看8001端口

netstat -na | grep 8001 


int main(void){

int sockfd=0;

/*socket 创建文件描述符*/

sockfd=socket(AF_INET,SOCK_STREAM,0);

if(sockfd == -1){

perror("fun socket\n");

exit(0);

}

/*bind 绑定地址和端口*/

/*struct sockaddr {

sa_family_t sa_family;

char        sa_data[14];

struct sockaddr_in {

uint8_t  sin_len; 4

sa_family_t  sin_family; 4

in_port_t sin_port; 2

struct in_addr sin_addr; 4

char sin_zero[8]; 8

};

}*/

struct sockaddr_in srvaddr;

srvaddr.sin_family = AF_INET;

srvaddr.sin_port = htons(8001);

srvaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

if( bind(sockfd, (struct sockaddr *) &srvaddr,sizeof(srvaddr)) < 0){

perror("fun bind\n");

exit(0);

}

/*listen 开启监听 同时监听数量

调用listen之后sockfd变成被动套接字,只能接受链接不能主动发送

*/

if(listen(sockfd,SOMAXCONN) < 0){

perror("fun listen\n");

exit(0);

}

/*accept */

struct sockaddr_in peeraddr;

socklen_t peerlen=sizeof(peeraddr);

unsigned int conn = 0;

conn = accept(sockfd,(struct sockaddr *) &peeraddr,(socklen_t *) &peerlen);

if(conn == -1){

perror("fun accept\n");

exit(0);

}

printf("perradd:%s\n perrport:%d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port));

char revbuf[1024] = {0};

/*read write*/

while(1){

int ret = read(conn,revbuf,sizeof(revbuf));

if(ret == 0){

//收到0数据包说明对方已经关闭

printf("对方已经关闭\n");

exit(0);

}

else if(ret < 0){

perror("读数据失败\n");

exit(0);

}

fputs(revbuf,stdout);//服务器收到数据,打印屏幕

write(conn,revbuf,ret);

}

return 0;

}


客户端

int main(void){

int sockfd=0;

/*socket 创建文件描述符*/

sockfd=socket(AF_INET,SOCK_STREAM,0);

if(sockfd == -1){

perror("fun socket\n");

exit(0);

}

/*bind 绑定地址和端口*/

/*struct sockaddr {

sa_family_t sa_family;

char        sa_data[14];

struct sockaddr_in {

uint8_t  sin_len; 4

sa_family_t  sin_family; 4

in_port_t sin_port; 2

struct in_addr sin_addr; 4

char sin_zero[8]; 8

};

}*/

struct sockaddr_in srvaddr;

srvaddr.sin_family = AF_INET;

srvaddr.sin_port = htons(8001);

srvaddr.sin_addr.s_addr = inet_addr("127.0.0.1");

if(connect(sockfd,(struct sockaddr *)&srvaddr,sizeof(srvaddr)) < 0){

perror("connect error\n");

exit(0);

}

char revbuf[1024] = {0};

char sendbuf[1024] = {0};

while(fgets(sendbuf,sizeof(sendbuf),stdin) != NULL){

//向服务器上写数据

write(sockfd,sendbuf,sizeof(sendbuf));

//从服务器上读数据

read(sockfd,revbuf,sizeof(revbuf));

//打印到屏幕

fputs(revbuf,stdout);

memset(revbuf,0,sizeof(revbuf));

memset(sendbuf,0,sizeof(sendbuf));

}

close(sockfd);

return 0;

}

你可能感兴趣的:(socket API)