#include "../lib/my.h"
typedef struct{
char name[20];
int age;
int id;
}info_t;
int main()
{
//1. 创建套接字
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0)
{
perror("socket");
exit(-1);
}
//地址信息结构体填充
struct sockaddr_in selfAddr;
selfAddr.sin_family = AF_INET;
selfAddr.sin_port = htons(7890);
selfAddr.sin_addr.s_addr = htonl(INADDR_ANY);
//2. 绑定
int ret = bind(sockfd, (struct sockaddr*)&selfAddr, sizeof(selfAddr));
if(ret < 0)
{
perror("bind");
close(sockfd);
exit(-1);
}
//3. 监听
int retListen = listen(sockfd, 10);
if(retListen < 0)
{
perror("listen");
close(sockfd);
exit(-1);
}
//4. 等待连接
int newSockfd = accept(sockfd, NULL, NULL);
if(newSockfd < 0)
{
perror("accept");
close(sockfd);
exit(-1);
}
//5. 处理数据
info_t info;
ssize_t retR = read(newSockfd, &info, sizeof(info));
if(retR < 0)
{
perror("read");
close(sockfd);
close(newSockfd);
exit(-1);
}
printf("name:%s age:%d id:%d\n", info.name, info.age, info.id);
//6. 关闭套接字
close(sockfd);
close(newSockfd);
return 0;
}
一转眼已经在华清学习一个多月了,从C语言基础到Linux网络编程,每天都在进步。