欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

udp编程套接字代码

程序员文章站 2022-03-04 20:45:28
...

server.c

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


int main(int argc, char* argv[])
{

    if(argc!=3)
    {
        printf("Useage:[IP] [PORT]\n");
        return 1;
    }


    int sock=socket(AF_INET,SOCK_DGRAM,0);

    if(sock<0)
    {
        perror("socket");
        return 2;
    }

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

    if(bind(sock,(struct sockaddr*)&local, sizeof(local))<0)
    {
        perror("bind");
        return 3;
    }

    char buf[8192];

    struct sockaddr_in client;
    while(1)
    {
        socklen_t len = sizeof(client);
        
        ssize_t s = recvfrom(sock ,buf,sizeof(buf)-1, 0, (struct sockaddr*)&client, &len);
       
        if(s>0)
        {
            buf[s]=0;
            printf("[%s:%d]: %s \n", inet_ntoa(client.sin_addr), ntohs(client.sin_port),buf); 

            sendto(sock,buf, strlen(buf), 0, (struct sockaddr*)&client, len);
        }
    }

    return 0;
}

client.c

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


int main(int argc, char* argv[])
{

    if(argc!=3)
    {
        printf("Useage:[IP] [PORT]\n");
        return 1;
    }


    int sock=socket(AF_INET,SOCK_DGRAM,0);

    if(sock<0)
    {
        perror("socket");
        return 2;
    }

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

    char buf[8196];
    struct sockaddr_in peer;
    socklen_t len = sizeof(peer);
     
    while(1)
    {
         printf("Please Enter Your words:");
         fflush(stdout);

        ssize_t s = read(0, buf, sizeof(buf)-1);
       
        if(s>0)
        {
            buf[s-1]=0;
           
            sendto(sock, buf, strlen(buf), 0, (struct sockaddr*)&server, sizeof(server));
        
            ssize_t _s = recvfrom(sock, buf, sizeof(buf)-1, 0, (struct sockaddr*)&peer, &len);
            
            if(_s>0)
            {
                buf[s-1]=0;
                printf("server echo:%s\n", buf);
            }

        }
    }

    return 0;
}

Makefile

.PHONY:all
all:server client

server:server.c
	gcc -o [email protected] $^

client:client.c
	gcc -o [email protected] $^

.PHONY:clean
clean:
	rm server client

 

相关标签: udp