服务端代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
assert(sockfd != -1);
struct sockaddr_in saddr, caddr;
memset(&saddr, 0, sizeof(saddr));
saddr.sin_family = AF_INET;
saddr.sin_port = htons(6000);
saddr.sin_addr = inet_addr("192.168.1.109");//改成自己的服务器Ip
int res = bind(sockfd, (struct sockaddr, sizeof(saddr)));
assert(res != -1);
res = listen(sockfd, 5);
assert(res != -1);
while (1)
{
int len = sizeof(caddr);
int c accept(socfd, (struct sockaddr*)&caddr, &len);
if (c < 0)
{
continue;
}
printf("accept c =%d ,if =%s,port %d\n", c, inet_ntoa(caddr, sin_addr), ntohs(caddr, sin_port));
while (1)
{
char buff[128] = [0];
int n = recv(c, buff, 1, 0);
if (n <= 0)
{
break;
}
printf("buff =%s\n", buff);
send(c, "ok", 2, 0);
{
close(c);
}
}
}
}