• [国嵌攻略][092][UDP网络程序设计]


    server.c

    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <strings.h>
    #include <stdio.h>
    
    #define SERVER_PORT 3333
    
    void main(){
        //创建标识
        int serverfd;
        
        serverfd = socket(AF_INET, SOCK_DGRAM, 0);   //建立UDP连接
        
        //绑定地址
        struct sockaddr_in serverAddr;
        
        serverAddr.sin_family = AF_INET;                   //设置协议
        serverAddr.sin_port = htons(SERVER_PORT);          //设置端口
        serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);    //设置地址
        bzero(serverAddr.sin_zero, 8);                     //设置为零
        
        bind(serverfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
        
        //接收数据
        char buffer[2048];
        struct sockaddr_in clientAddr;
        socklen_t clientAddrLen;
        
        clientAddrLen = sizeof(struct sockaddr);
        recvfrom(serverfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&clientAddr, &clientAddrLen);
        
        //显示数据
        char *clientIPAddr;
        
        clientIPAddr = (char *)inet_ntoa(clientAddr.sin_addr.s_addr);
        printf("server recvice from %s:
    %s", clientIPAddr, buffer);
        
        //关闭连接
        close(serverfd);
    }

    client.c

    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <strings.h>
    #include <stdio.h>
    
    #define SERVER_PORT 3333
    
    int main(int argc, char **argv){
        //参数检查
        if(argc != 2){
            printf("Usage:
    	%s <ip address>
    ", argv[0]);
            return -1;
        }
        
        //创建标识
        int clientfd;
        
        clientfd = socket(AF_INET, SOCK_DGRAM, 0);   //建立UDP连接
        
        //输入数据
        char buffer[2048];
        
        printf("client send to %s:
    ", argv[1]);
        fgets(buffer, sizeof(buffer), stdin);
        
        //发送数据
        struct sockaddr_in serverAddr;
        
        serverAddr.sin_family = AF_INET;                   //设置协议
        serverAddr.sin_port = htons(SERVER_PORT);          //设置端口
        serverAddr.sin_addr.s_addr = inet_addr(argv[1]);   //设置地址
        bzero(serverAddr.sin_zero, 8);                     //设置为零
        
        sendto(clientfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr));
        
        //关闭连接
        close(clientfd);
        
        return 0;
    }
  • 相关阅读:
    Selenium2+python自动化30-引入unittest框架【转载】
    GitHub上整理的一些工具
    git使用教程2-更新github上代码【转载】
    git使用教程1-本地代码上传到github【转载】
    Selenium2+python自动化46-js解决click失效问题【转载】
    linux_常用命令_2
    linux_磁盘体系
    linux_定时任务
    yum错误,Cannot find a valid baseurl for repo: base 和 No more mirrors to try
    linux批量添加10个用户并将其随机密码和用户名写入文件
  • 原文地址:https://www.cnblogs.com/d442130165/p/5233603.html
Copyright © 2020-2023  润新知