server.c
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT 8003
#define MSG_BUF_SIZE 128
int main(void)
{
int sockfd;
struct sockaddr_in my_addr, their_addr;
int addr_len, numbytes;
char buffer[MSG_BUF_SIZE];
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
fprintf(stderr, "socket error");
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");
exit(1);
}
addr_len = sizeof(struct sockaddr);
if ((numbytes = recvfrom(sockfd, buffer, MSG_BUF_SIZE, 0, (struct sockaddr *)&their_addr, &addr_len)) == -1)
{
fprintf(stderr, "recvfrom error");
exit(1);
}
printf("got packet from %s\n", inet_ntoa(their_addr.sin_addr));
printf("packet is %d bytes long\n", numbytes);
buffer[numbytes] = '\0';
printf("packet contains \"%s \"\n", buffer);
close(sockfd);
}
client.c
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT 8003
int main(int argc, char *argv[])
{
int sockfd;
struct sockaddr_in their_addr;
struct hostent *hostname;
int num_bytes;
if (argc != 3)
{
fprintf(stderr, "usage: talker hostname message\n");
exit(1);
}
if ((hostname = gethostbyname(argv[1])) == NULL)
{
fprintf(stderr, "gethostbyname error");
exit(1);
}
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
fprintf(stderr, "socket");
exit(1);
}
their_addr.sin_family = AF_INET;
their_addr.sin_port = htons(SERVER_PORT);
their_addr.sin_addr = *((struct in_addr *)hostname->h_addr);
bzero(&(their_addr.sin_zero), 8);
if ((num_bytes = sendto(sockfd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1)
{
fprintf(stderr, "sendto error");
exit(1);
}
printf("sent %d bytes to %s\n", num_bytes, inet_ntoa(their_addr.sin_addr));
close(sockfd);
return 0;
}
编译:
gcc server.c -o server
gcc client.c -o client
执行:
打开一终端执行:./server
打开另一终端执行:./client 127.0.0.1
阅读(1403) | 评论(0) | 转发(0) |