客户端:
#include <stdio.h>
#include <stdlib.h>
服务端
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAXLINE 50
int main(void)
{
int s_fd;
int b_fd;
int l_fd;
int a_fd;
struct sockaddr_in server_add;
//server_add清0
memset(&server_add, 0, sizeof(server_add));
char buf[MAXLINE];
s_fd = socket(AF_INET, SOCK_STREAM, 0);
if(s_fd < 0)
{
perror("socket");
exit(1);
}
server_add.sin_family = AF_INET;
server_add.sin_port = htons(8888);
server_add.sin_addr.s_addr = inet_addr("192.168.107.128");
//向系统登记你关心IP地址和端口号
b_fd = bind(s_fd, (struct sockaddr *)&server_add, \
sizeof(struct sockaddr));
if(b_fd < 0)
{
perror("bind");
exit(1);
}
//监听
l_fd = listen(s_fd, 5);
if(l_fd < 0)
{
perror("listen");
exit(1);
}
//接受客户端的连接
a_fd = accept(s_fd, NULL, NULL);
if(a_fd < 0)
{
perror("accept");
exit(1);
}
printf("accept sucess\n");
while(1)
{
fgets(buf, 50, stdin);
write(a_fd, buf, 50);
}
close(s_fd);
return 0;
}
编译:
gcc -o client client.c
gcc -o server server.c
先运行服务器
./server
再运行客户端
./client