Chinaunix首页 | 论坛 | 博客
  • 博客访问: 342698
  • 博文数量: 72
  • 博客积分: 2130
  • 博客等级: 大尉
  • 技术积分: 857
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-05 16:10
文章分类

全部博文(72)

文章存档

2010年(5)

2009年(14)

2008年(53)

分类: LINUX

2009-07-03 17:27:34

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) |
0

上一篇:TCP网络编程实例

下一篇:ubuntu中pdf乱码

给主人留下些什么吧!~~