Linux下用C语言实现udp模式下两个客户端间的通信

需要用到的知识:Linux C网络编程相关知识以及简单的多线程操作

两个客户端的代码是一样的,只要把端口号换一下,一个客户端中的本机端口MY_PORT相当于另一个客户端的目的端口DEST_PORT

#include
#include
#include
#include
 
#include
#include

#define MY_IP "127.0.0.1"
#define MY_PORT 52100

#define DEST_IP "127.0.0.1"
#define DEST_PORT 52200

typedef struct my_sock_cb
{
    int fd;
    struct sockaddr_in addr_my;
    int addrlen_my;
}my_sock_cb;

typedef struct dest_sock_cb
{
    int fd;
    struct sockaddr_in addr_dest;
    int addrlen_dest;
}dest_sock_cb;

my_sock_cb mysock = {-1};
dest_sock_cb destsock = {-1};

int initsocket()
{
    mysock.fd = socket(AF_INET, SOCK_DGRAM, 0);
    destsock.fd = socket(AF_INET, SOCK_DGRAM, 0);
    if( mysock.fd<0 || destsock.fd<0 )
    {
        perror("create socket error!\n");
        exit(1);
    }

    mysock.addr_my.sin_family = AF_INET;
    mysock.addr_my.sin_addr.s_addr = inet_addr(MY_IP);
    mysock.addr_my.sin_port = htons(MY_PORT);
    mysock.addrlen_my = sizeof(struct sockaddr_in);
  
    destsock.addr_dest.sin_family = AF_INET;
    destsock.addr_dest.sin_addr.s_addr = inet_addr(DEST_IP);
    destsock.addr_dest.sin_port = htons(DEST_PORT);
    destsock.addrlen_dest = sizeof(struct sockaddr_in);

    int ret = bind(mysock.fd, (struct sockaddr*)&mysock.addr_my, mysock.addrlen_my);
    if(ret == -1)
    {
        perror("bind.");
        exit(1);
    }

    return 0;
}

void* recv_msg(void* sock)
{
    my_sock_cb *mysock = (my_sock_cb*)sock;
    
    struct sockaddr_in addr_other;
 
    char recvbuf[256];
    while(1)
    {
        recvfrom(mysock->fd, recvbuf, 256, 0, (struct sockaddr*)&addr_other, &mysock->addrlen_my);
        printf("other:>%s\n", recvbuf);
        if( !strcmp(recvbuf, "exit") )
            break;
    }
 
    close(mysock->fd);
}

void* send_msg(void* sock)
{
    dest_sock_cb *destsock = (dest_sock_cb*)sock;
    char sendbuf[256];
    while(1)
    {
        printf("Input:>");
        scanf("%s",sendbuf);
        sendto(destsock->fd, sendbuf, strlen(sendbuf)+1, 0, 
(struct sockaddr*)&destsock->addr_dest,destsock->addrlen_dest);
        if( !strcmp(sendbuf,"exit") )
            break;
    }
    close(destsock->fd);
}

int main()
{
    initsocket();
    my_sock_cb *sock1 = &mysock;
    dest_sock_cb *sock2 = &destsock; 
    
    void* recv_msg(void*);
    void* send_msg(void*);

    pthread_t t1,t2;
    pthread_create(&t2, NULL, send_msg, (void *)sock2);
    pthread_create(&t1, NULL, recv_msg, (void *)sock1);

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    
    return 0;
}

参考自:https://blog.csdn.net/manonghouyiming/article/details/79803403

你可能感兴趣的:(C)