linux 基础版udp server、client(可直接编译)

服务器代码 server_udp.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <ctype.h>
typedef struct sockaddr SA;
typedef struct sockaddr_in SA4;
int main(void) {
    int s_fd;
    int i = 0;
    SA4 server, client;
    char buf[10240] = {0};

    s_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == s_fd) {
        perror("socket");
        return 1;
    }

    server.sin_family = AF_INET;
    server.sin_port = htons(7779);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    int b = bind(s_fd, (SA *)&server, sizeof(server));
    if(-1 == b) {
        perror("bind");
        return 2;
    }
    while(1) {

        int cli_len = sizeof(client);
        int r = recvfrom(s_fd, buf, 10240, 0, (SA *)&client, &cli_len);
        printf("接收到信息:%s\n", buf);

        for(i = 0; i < r; i++) {
            buf[i] = toupper(buf[i]);
        }

        sendto(s_fd, buf, r, 0, (SA *)&client, sizeof(client));
        printf("发出的信息:%s\n", buf);
    }
    close(s_fd);
    return 0;
}

客户端代码client_udp.c

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
int main(void) {
    int s_fd;
    char buf[10240] = "hello,world";

    s_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == s_fd) {
        perror("socket");
        return 1;
    }
    struct sockaddr_in server;

    server.sin_family = AF_INET;
    server.sin_port = htons(7779);
    inet_pton(AF_INET, "39.106.209.165", &server.sin_addr);

    sendto(s_fd, buf, strlen(buf)+1, 0, (struct sockaddr *)&server, sizeof(server));

    bzero(buf, sizeof(buf));
    int r = recvfrom(s_fd, buf, sizeof(buf), 0, NULL, NULL);

    write(1, buf, r);
    write(1, "\n", 2);
    close(s_fd);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值