UDP套接字编程

//使用UDP实现UDP回射服务器
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
void dg_echo(int sockfd, struct sockaddr *pcliaddr, socklen_t clilen)
{
    char buffer[MAXLINE];
    int n;
    socklen_t len;
    memset(buffer, 0, MAXLINE);
    while(1)
    {
        len = clilen;
        n = recvfrom(sockfd, buffer, MAXLINE, 0, pcliaddr, &len);
        printf("%s\n", buffer);
        sendto(sockfd, buffer, n, 0, pcliaddr, len);
        memset(buffer, 0, MAXLINE);
    }
}

int main()
{
    int sockfd;//套接字描述符
    struct sockaddr_in server_sockaddr, client_sockaddr;//本地地址和端口号

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)//创建一个数据报套接字
    {
        fprintf(stderr, "Socket failed\n");
        exit(EXIT_FAILURE);
    }

    bzero(&server_sockaddr, sizeof(server_sockaddr));//结构体清零
    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_port = htons(9877);
    server_sockaddr.sin_addr.s_addr = htonl(INADDR_ANY);//通配地址,存储要按网络字节序的顺序存储
    if(bind(sockfd, (struct sockaddr*)&server_sockaddr, sizeof(server_sockaddr)) < 0)//绑定本地地址和端口号
    {
        fprintf(stderr, "Bind failed\n");
        exit(EXIT_FAILURE);
    }

    dg_echo(sockfd, (struct sockaddr*)&client_sockaddr, sizeof(client_sockaddr));//处理客户端的请求
    exit(0);
}
//客户端程序
//使用connect
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096
void dg_cli(FILE *fp, int sockfd, const struct sockaddr *pservaddr, socklen_t servlen)
{
    int n;
    char send_buffer[MAXLINE], recv_buffer[MAXLINE+1];//发送缓冲区、接收缓冲区

    if(connect(sockfd, (struct sockaddr*)pservaddr, servlen) < 0)//指定目的主机地址和端口号,之前未调用connect异步错误不会返回给客户,调用可以返回
    {
        fprintf(stderr, "Connect failed\n");
        exit(EXIT_FAILURE);
    }

    while(fgets(send_buffer, MAXLINE, fp) != NULL)//从标准输入
    {
        write(sockfd, send_buffer, strlen(send_buffer));
        n = read(sockfd, recv_buffer, MAXLINE);
        recv_buffer[n] = 0;
        fputs(recv_buffer, stdout);
    }
}

int main(int argc, char **argv)
{
    int sockfd;//套接字描述符
    struct sockaddr_in server_sockaddr;//IPv4套接字地址结构

    if((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        fprintf(stderr, "Socket failed\n");
        exit(EXIT_FAILURE);
    }
    else
        printf("Socket success\n");

    bzero(&server_sockaddr, sizeof(server_sockaddr));
    server_sockaddr.sin_family = AF_INET;
    server_sockaddr.sin_port = htons(9877);
    inet_pton(AF_INET, argv[1], &server_sockaddr.sin_addr);

    dg_cli(stdin, sockfd, (struct sockaddr*)&server_sockaddr, sizeof(server_sockaddr));
}

你可能感兴趣的:(Linux系统编程)