主函数:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "__%d__:", __LINE__);\
perror(msg);\
}while(0)
#define PORT 8888 //1024~49151
#define IP "10.0.12.9" //本机IP,ifconfig查找
int main(int argc, const char *argv[])
{
//创建流式套接字
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//允许端口快速重用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用\n");
//填充地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET; //必须填AF_INET
sin.sin_port = htons(PORT); //网络字节序的端口号1024~49151
sin.sin_addr.s_addr = inet_addr(IP); //本机IP,ifconfig查找
//将IP和端口绑定到套接字上
if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
//将套接字设置为被动监听状态;
if(listen(sfd, 10) < 0)
{
ERR_MSG("listen");
return -1;
}
printf("监听成功\n");
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
//取出新的文件描述符
int newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s:%d] newfd=%d 连接成功\n", inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd);
char buf[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf, sizeof(buf));
//newfd中读取数据
res = recv(newfd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
fprintf(stderr, "newfd = %d 客户端关闭\n", newfd);
break;
}
printf("newfd=%d : %s\n", newfd, buf);
strcat(buf, "*-*");
//发送数据到客户端
if(send(newfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}printf("发送到newfd = %d客户端成功\n", newfd);
}
//关闭文件描述符
close(sfd);
close(newfd);
return 0;
}
测试:
允许端口快速重用
监听成功