Skip to content

Instantly share code, notes, and snippets.

@padenot
Created November 29, 2010 10:27
Show Gist options
  • Save padenot/719797 to your computer and use it in GitHub Desktop.
Save padenot/719797 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define BUFFER_SIZE 128
const int TAILLE_FILE = 3;
/** Fonction permettant l'initialisation d'une struct du type sockaddr */
void init_sockaddr(struct sockaddr_in *name, char* hostname, int port)
{
struct hostent *hostinfo;
name->sin_family = AF_INET;
name->sin_port = htons(port);
hostinfo = gethostbyname(hostname);
if(hostinfo == NULL)
{
fprintf(stderr,"Erreur, l'host %s est inconnu", hostname);
exit(1);
}
name->sin_addr = *(struct in_addr *) hostinfo->h_addr_list[0];
}
int bindSocket(char* hostname, int port, int fd)
{
struct sockaddr_in addr;
/* Initialisation de la structure */
init_sockaddr(&addr, hostname, port);
if(bind(fd, (struct sockaddr *) &addr, sizeof(addr)) == -1 )
return -1;
return 0;
}
int listenSocket(unsigned int taille, int fd)
{
if(listen(fd , taille) == -1)
return -1;
return 0;
}
int acceptSocket(int fd)
{
int fd_socket;
if( (fd_socket = accept(fd, NULL, NULL)) == -1)
perror("accept"), exit(1);
return fd_socket;
}
void tcp(char* hostname,int port)
{
char buffer[BUFFER_SIZE];
int numRead;
int clientFD;
int sockService;
/* Mise en place de la socket de service. */
if((sockService = socket(PF_INET,SOCK_STREAM, 0)) == -1)
perror("socket Service"),exit(1);
if(bindSocket(hostname,port,sockService))
perror("bindSocket"),exit(1);
if(listenSocket(TAILLE_FILE, sockService))
perror("listenSocket"), exit(1);
/* On attend un client. */
clientFD = acceptSocket(sockService);
/* Lecture des données envoyées sur la socket, puis écriture de celle-ci sur
* stdout.
*/
while((numRead = read(clientFD, buffer, BUFFER_SIZE - 1)) > 0)
{
buffer[numRead] = 0;
puts(buffer);
}
close(sockService);
}
void usage(char* name)
{
fprintf(stderr,"Usage: %s [port] \n",name);
exit(1);
}
int main(int argc,char** argv)
{
int port;
if(argc != 3)
usage("name");
if(sscanf(argv[2], "%d" ,&port) != 1)
usage(argv[0]);
tcp(argv[1], port);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment