matheus__serpa icon

Socket

matheus__serpa | PRO | 03/30/15 02:33:37 AM UTC | 0 ⭐ | 382 👁️ | Never ⏰ | []
C |

2.51 KB

|

None

|

0 👍

/

0 👎

/* http://www.linuxhowtos.org/C_C++/socket.htm */
 
#include <stdio.h>
#include <stdlib.h>    /* atoi */  
#include <unistd.h>
 
#include <strings.h>   /* bzero */
#include <arpa/inet.h> /* htons */
 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
 
#define BUFFER_SIZE 256
#define BACKLOG 5 /* defines the maximum length to which the queue of pending connections. */
 
int main(int argc, char **argv){
    
    if(argc != 3){
        fprintf(stderr, "Usage: %s <PORT> <FILE_TO_SEND> \n", argv[0]);
        exit(EXIT_FAILURE);
    }
 
    int socketFD, newsocketFD; /* file descriptors. */
    int port = atoi(argv[1]); /* port number. */
    socklen_t clientSize /* size of the address of the client. */;
    int n; /* number of characters read or written. */
    char buffer[BUFFER_SIZE]; /* server reads from the socket into this buffer. */
    struct sockaddr_in serv_addr, cli_addr;
 
    socketFD = socket(AF_INET, SOCK_STREAM, 0); /* create an endpoint for communication. */
    if(socketFD < 0){
        fprintf(stderr, "Socket doesn't opening. \n");
        exit(EXIT_FAILURE);
    }
 
    bzero((char *) &serv_addr, sizeof(serv_addr)); /* sets all values in serv_addr to zero. */
 
    serv_addr.sin_family = AF_INET; /* code for the address family. */
    serv_addr.sin_port = htons(port); /* convert the port to network byte order.*/
    serv_addr.sin_addr.s_addr = INADDR_ANY; /* IP address of the host. */
 
    if(bind(socketFD, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0){ /* binds a socket to an address. */
        fprintf(stderr, "Socket doesn't binds to an address. \n");
        exit(EXIT_FAILURE);
    }
 
    listen(socketFD, BACKLOG); /* listen for connections on a socket. */
 
 
    clientSize = sizeof(cli_addr);
    newsocketFD = accept(socketFD, (struct sockaddr *) &cli_addr, &clilen); /* accept a connection on a socket. */
    if (newsocketFD < 0){
        fprintf(stderr, "Socket doesn't accept a new connection. \n");
        exit(EXIT_FAILURE);
    }
 
    bzero(buffer, BUFFER_SIZE); /* sets all values in buffer to zero. */
 
    n = read(newsocketFD, buffer, BUFFER_SIZE - 1); /* read from a file descriptor. */
 
    if(n < 0){
        fprintf(stderr, "Socket doesn't read to the client socket. \n");
        exit(EXIT_FAILURE);
    }
 
    printf("Here is the message: %s\n", buffer);
 
    n = write(newsocketFD, "I got your message", 18); /* write to a file descriptor. */
 
    if(n < 0){
        fprintf(stderr, "Socket doesn't write to the client socket. \n");
        exit(EXIT_FAILURE);
    }
 
    /* close a file descriptor. */
    close(newsocketFD);
    close(socketFD);
 
    return 0;
}

Comments