程式語言 - GNU - C/C++ - UDP Server、Client



參考資訊:
https://www.geeksforgeeks.org/udp-client-server-using-connect-c-implementation/

server.c

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <arpa/inet.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 

int main(int argc, char **argv) 
{
    int r = 0;
    int fd = 0;
    int len = 0;
    char buf[1024] = {0};
    struct sockaddr_in servaddr = {0};
    const char *hello = "hello from server !";

    if (argc != 3) {
        printf("usage: %s ip port\n", argv[0]);
        return 0;
    }

    fd = socket(AF_INET, SOCK_DGRAM, 0);
    servaddr.sin_addr.s_addr = inet_addr(argv[1]); // INADDR_ANY
    servaddr.sin_port = htons(atoi(argv[2]));
    servaddr.sin_family = AF_INET;

    if (bind(fd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0) {
        perror("bind");
        return -1;
    }

    len = sizeof(struct sockaddr_in);
    r = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&servaddr, &len);
    printf("%s\n", buf);

    sendto(fd, hello, strlen(hello), 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
    close(fd);
    return 0;
}

client.c

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <arpa/inet.h> 
#include <sys/socket.h> 
#include <sys/types.h> 
#include <netinet/in.h> 
#include <unistd.h> 
  
int main(int argc, char **argv) 
{    
    int r = 0; 
    int fd = -1;
    int len = 0;
    char buf[1024] = {0};
    struct sockaddr_in servaddr = {0}; 
    const char *hello = "hello from client !";

    if (argc != 3) {
        printf("usage: %s ip port\n", argv[0]);
        return 0;
    }

    servaddr.sin_addr.s_addr = inet_addr(argv[1]);
    servaddr.sin_port = htons(atoi(argv[2]));
    servaddr.sin_family = AF_INET;

    fd = socket(AF_INET, SOCK_DGRAM, 0); 
    sendto(fd, hello, strlen(hello), 0, (struct sockaddr*)&servaddr, sizeof(servaddr));

    len = sizeof(struct sockaddr_in);
    recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr*)&servaddr, (socklen_t *)&len);
    printf("%s\n", buf);
    close(fd);
    return 0;
}

編譯、執行

$ gcc server.c -o server
$ gcc client.c -o client

$ ./server 127.0.0.1 9999 &
$ ./client 127.0.0.1 9999
hello from client !
hello from server !