客户端代码:
/* client */
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <errno.h>
#define PORT 8848
#define MAXDATASIZE 100
int main(int argc, char *argv[])
{
char hostname[100];
gethostname(hostname,sizeof(hostname));
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~%s\n",hostname);
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
struct sockaddr_in serv_addr;
if (argc != 2)
{
fprintf(stderr, "usage: cilent hostname\n");
return 0;
}
if ((he = gethostbyname(argv[1])) == NULL)
{
fprintf(stderr, "gethostbyname error!\n");
return 0;;
}
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
fprintf(stderr, "socket error!\n");
return 0;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(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");
return 0;
}
if ((numbytes = read(sockfd, buf, MAXDATASIZE)) == -1)
{
fprintf(stderr, "read error!\n");
return 0;
}
buf[numbytes] = '\0';
printf("Received: %s", buf);
close(sockfd);
}
服务器端代码:
/* server */
#include <stdio.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <errno.h>
#define PORT 8848
#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");
return 0;
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(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");
return 0;
}
if (listen(sockfd, BACKLOG) == -1)
{
fprintf(stderr, "listen error!\n");
return 0;
}
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);
return 0;
}
close(conn_fd);
while(waitpid(-1, NULL, WNOHANG) > 0);
}
}