1 /* Javier Abellán, 20 Junio 2000
3 * Funciones para abrir/establecer sockets de un cliente con un servidor.
6 * 4 Septiembre 2003. Añadida función Abre_Conexion_Udp()
11 * Includes del sistema
13 #include <sys/types.h>
14 #include <sys/socket.h>
16 #include <netinet/in.h>
23 * Conecta con un servidor Unix, en la misma maquina.
24 * Devuelve descriptor de socket si todo es correcto, -1 si hay error.
26 int Abre_Conexion_Unix (char *Servicio)
28 struct sockaddr_un Direccion;
31 strcpy (Direccion.sun_path, Servicio);
32 Direccion.sun_family = AF_UNIX;
34 /* Se abre el descriptor del socket */
35 Descriptor = socket (AF_UNIX, SOCK_STREAM, 0);
39 /* Se establece la conexion.
40 * Devuelve 0 si todo va bien, -1 en caso de error */
43 (struct sockaddr *)&Direccion,
44 strlen (Direccion.sun_path) + sizeof (Direccion.sun_family)) == -1)
53 * Conecta con un servidor remoto a traves de socket INET
55 int Abre_Conexion_Inet (
59 struct sockaddr_in Direccion;
60 struct servent *Puerto;
65 Puerto = getservbyname (Servicio, "tcp");
71 Host = gethostbyname (Host_Servidor);
75 Direccion.sin_family = AF_INET;
76 Direccion.sin_addr.s_addr = ((struct in_addr *)(Host->h_addr))->s_addr;
77 // Direccion.sin_port = Puerto->s_port;
78 Direccion.sin_port = 15557;
80 Descriptor = socket (AF_INET, SOCK_STREAM, 0);
86 (struct sockaddr *)&Direccion,
87 sizeof (Direccion)) == -1)
97 * Prepara un socket para un cliente UDP.
98 * Asocia un socket a un cliente UDP en un servicio cualquiera elegido por el sistema,
99 * de forma que el cliente tenga un sitio por el que enviar y recibir mensajes.
100 * Devuelve el descriptor del socket que debe usar o -1 si ha habido algún error.
102 int Abre_Conexion_Udp ()
104 struct sockaddr_in Direccion;
107 /* Se abre el socket UDP (DataGRAM) */
108 Descriptor = socket (AF_INET, SOCK_DGRAM, 0);
109 if (Descriptor == -1)
114 /* Se rellena la estructura de datos necesaria para hacer el bind() */
115 Direccion.sin_family = AF_INET; /* Socket inet */
116 Direccion.sin_addr.s_addr = htonl(INADDR_ANY); /* Cualquier dirección IP */
117 Direccion.sin_port = htons(0); /* Dejamos que linux eliga el servicio */
119 /* Se hace el bind() */
122 (struct sockaddr *)&Direccion,
123 sizeof (Direccion)) == -1)
129 /* Se devuelve el Descriptor */