server.c
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT 8003
#define BACKLOG 10
int main(void)
{
int sockfd, conn_fd;
struct sockaddr_in my_addr;
struct sockaddr_in their_addr;
int sin_size;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "socket error!\n");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(SERVER_PORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "bind error!\n");
exit(1);
}
if (listen(sockfd, BACKLOG) == -1)
{
fprintf(stderr, "listen error!\n");
exit(1);
}
while (1)
{
sin_size = sizeof(struct sockaddr_in);
if ((conn_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
{
fprintf(stderr, "accept error!\n");
continue;
}
printf("server: got connection from %s\n", inet_ntoa(their_addr.sin_addr));
if (!fork())
{
if (send(conn_fd, "Hello, world!\n", 14, 0) == -1)
fprintf(stderr, "send error!\n");
close(conn_fd);
exit(0);
}
close(conn_fd);
while(waitpid(-1, NULL, WNOHANG) > 0);
}
}
client.c
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT 8003
#define MAXDATASIZE 100
int main(int argc, char *argv[])
{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in serv_addr;
if (argc != 2)
{
fprintf(stderr, "usage: cilent hostname\n");
exit(1);
}
if ((he = gethostbyname(argv[1])) == NULL)
{
fprintf(stderr, "gethostbyname error!\n");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "socket error!\n");
exit(1);
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(SERVER_PORT);
serv_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(serv_addr.sin_zero), 8);
if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(struct sockaddr)) == -1)
{
fprintf(stderr, "connect error!\n");
exit(1);
}
if ((numbytes = read(sockfd, buf, MAXDATASIZE)) == -1)
{
fprintf(stderr, "read error!\n");
exit(1);
}
buf[numbytes] = '\0';
printf("Received: %s", buf);
close(sockfd);
}
编译:
gcc server.c -o server
gcc client.c -o client
执行:
打开一终端执行:./server
打开另一终端执行:./client 127.0.0.1
阅读(4004) | 评论(0) | 转发(0) |