UDP Sockets in C

48,109

Solution 1

I have written a UDP server-client in C , where the client sends a registration number and the server gives a name as the feedback.

SERVER

0. Variable initialization
1. sock()
2. bind()
3. recvfrom()
4. sendto()

CLIENT

0. gethostbyname()
1. sock()
2. bzero()
4. sendto()
5. recvfrom()

Hope it helps. You can find the example code here udp server/client

Solution 2

accept is only used for connection oriented (STREAM) sockets. UDP is not stream, oriented, so there are no connections and you can't use accept(2) -- it will return EOPNOTSUPP.

Instead, you just read packets directly from the bound service socket (generally using recvfrom(2) so you can tell where thy came from, though you can use recv or just read if you don't care), afterwhich you can send packets back using the same socket (and generally using sendto(2))

Solution 3

Keep in mind that UDP is connectionless. It only sends packets, and is not suitable for sending files - unless the entire content fit in one UDP packet.

If you anyway want to send/receive UDP packets, you simply call sendto/recvfrom with the appropriate addresses.

Share:
48,109
mkluwe
Author by

mkluwe

Updated on October 14, 2020

Comments

  • mkluwe
    mkluwe over 3 years

    I'm working on a homework problem for class. I want to start a UDP Server that listens for a file request. It opens the file and sends it back to the requesting client with UDP.

    Heres the server code.

        // Create UDP Socket
        if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
            perror("Can't create socket");
            exit(-1);
        }
    
        // Configure socket
        memset(&server, 0, sizeof server);
        server.sin_family = AF_INET; // Use IPv4
        server.sin_addr.s_addr = htonl(INADDR_ANY); // My IP
        server.sin_port = htons(atoi(argv[1])); // Server Port
    
        // Bind socket
        if ((bind(sockfd, (struct sockaddr *) &server, sizeof(server))) == -1) {
            close(sockfd);
            perror("Can't bind");
        }
    
        printf("listener: waiting to recvfrom...\n");
        if (listen(sockfd, 5) == -1) {
            perror("Can't listen for connections");
            exit(-1);
        }
    
    while (1) {
        client_len = sizeof(struct sockaddr_in);
        newsockfd = accept(sockfd, (struct sockaddr*)&client,&client_len);
    
        if (newsockfd < 0) {
            perror("ERROR on accept");
        }
    
        // Some how parse request
        // I do I use recv or recvfrom?
        // I do I make new UDP socket to send data back to client?
    
        sendFile(newsockfd, filename);
    
        close(newsockfd);
    }
    
    close(sockfd);
    

    I'm kind of lost how do I recv data from the client? And how to I make a new UDP connection back to the client?