9.2网络-socket2_UDP通信 2015/8/7

UDP

recvfrom

阻塞等待客户端数去请求
接收客户端发送来的数据,和地址端口信息
#include

sendto

给客户端地址端口addr发送数据应答
#include

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <arpa/inet.h>

#define SERV_PORT 8000

int main(void)
{
    int sockfd;
    struct sockaddr_in servaddr, cliaddr;
    int n, i;
    char buf[256];
    char str[256];
    socklen_t cliaddrlen;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0); 

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));

    printf("Receiving ...\n");

    while (1) {
        cliaddrlen = sizeof(cliaddr);
        n = recvfrom(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&cliaddr, &cliaddrlen);  //接收

        printf("Rece: %s, PORT:%d\n", inet_ntop(AF_INET, &cliaddr.sin_addr, str, cliaddrlen), ntohs(cliaddr.sin_port));

        for (i = 0; i < n; i++)
            buf[i]  = toupper(buf[i]);
        sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&cliaddr, cliaddrlen);    //发送
        bzero(buf, sizeof(buf));
    }

    close(sockfd);
    return 0;
}

client.c

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <string.h>
#include <strings.h>

#define SERV_PORT 8000

int main(void)
{
    int sockfd;
    struct sockaddr_in servaddr;
    char buf[256];
    socklen_t servaddlen;
    int n;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0); 

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(SERV_PORT);
    inet_pton(AF_INET, "192.168.188.133",  &servaddr.sin_addr);

    while (fgets(buf, sizeof(buf), stdin) != NULL) {
        servaddlen = sizeof(servaddr);

        sendto(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&servaddr, servaddlen);  

        n = recvfrom(sockfd, buf, strlen(buf), 0, (struct sockaddr *)&servaddr, &servaddlen);
        write(STDOUT_FILENO, buf, n);
    }
    close(sockfd);
    return 0;
}

你可能感兴趣的:(网络,通信,UDP)