#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/sockets.h>#include <netinet/in.h>#include <arpa/inet.h>int main(int argc, char const*argv[]){if( argc >1){ int server_socket, client_socket, longitud_cliente, puerto; puerto =atoi( argv[1]); struct sockaddr_in server; struct sockaddr_in client;// Variables del server server.sin_family=AF_INET;// Protocolo TCP/IP server.sin_port=htons( puerto );// Puerto server.sin_addr.s_addr=INADDR_ANY;// Firewall (todos se puede conectar)bzero(&(server.sin_zero),8);// 8 posiciones llenadas con zeros// Crear socket del servidor en modo escucha// Familia de Protocolo, protocolo, autoif(( server_socket =socket(AF_INET,SOCKET_STREAM,0))){perror("No puede abrir el socket\n");return-1;}//Conectar socket a un puerto// Guardar config en serverif(bind( server_socket,(struct sockaddr *)&server,sizeof( sockaddr ))==-1){perror("No pude abrir el puerto %s\n", argv[1]);return-2;}// Poner el socket en modo escucha definiendo lim de colaif(listen( server_socket,5)==-1){perror("No pude ponerme en modo escucha");return-3;} longitud_cliente =sizeof( struct sockaddr_in );// Intentar recibir el primer clienteif((client_socket =accept( server, socket,(struct sockaddr *)&client,&longitud_cliente ))==-1){printf("No pudimos aceptar una conexion\n");return-4;} char str[INET_ADDRSTRLEN];// Priemara conexion a strinet_ntop(AF_INET,&(cliente.sin_addr), str,INET_ADDRSTRLEN);printf("Se conecto un cliente desde la ip %s:%d.Lo saludo\n", str, client.sin_port)// Mandando mensaje a la conexionsend( client_socket,"Bienvenido a mi servidor\n",26,0);printf("El saludo fue enviado\n");// Cerrar por completoshutdown( client_socket,2);shutdown( server_socket,2);}// EL usuario no ingreso el puerto por la linea de comandoselse{printf("Porfavor indique el puerto\n");return-5;}return0;}
Si usas windows aquí te dejo el código del Servidor traducido al windows que casi casi es parecido al que se usa en unix 😄
#include <winsock2.h>#include <winsock.h>#include <stdio.h>#include <string.h>int main(int argc, char **argv){if(argc <2){printf("indica un puerto");return-1;}WSADATA wsaData ={0};SOCKET socket_servidor;WORDPuertoW=(WORD)atoi( argv[1]);SOCKADDR_INServidor={0};SOCKADDR_INCliente={0};Servidor.sin_family=AF_INET;Servidor.sin_port=htons(PuertoW);Servidor.sin_addr.s_addr=INADDR_ANY;WSAStartup(MAKEWORD(2,2),&wsaData);if((socket_servidor =socket(AF_INET,SOCK_STREAM,IPPROTO_IP))==SOCKET_ERROR){printf("_ERROR_ : No se pudo abir el Socket");return-2;}if(bind( socket_servidor ,(SOCKADDR*)&Servidor,sizeof(Servidor))==SOCKET_ERROR){printf("Error : al abrir %s",argv[1]);closesocket(socket_servidor);return-3;}printf("Esperando clientes\n");listen(socket_servidor ,5); int Longitud=sizeof(SOCKADDR_IN);SOCKET socket_cliente =accept(socket_servidor,(SOCKADDR*)&socket_cliente,&Longitud);if(socket_cliente ==SOCKET_ERROR){printf("no pudimos aceptar la coneccion\n");return-4;} char buff[100];printf("Conectando [%s,%d] : %s",inet_ntoa(Cliente.sin_addr),htons(Cliente.sin_port),buff);send(socket_cliente,"Bienvenido a mi servidor.\n",26,0);printf("el saludo fue enviado\n");closesocket(socket_cliente);closesocket(socket_servidor);WSACleanup();return0;```
//Sockets, conección entre cliente y servidor //Ingresamos librerias #include <sys/sockets.h>//Llibreria de los Sockets#include <netinet/in.h>//Libreria de comunicación#include <arpa/inet.h>#include <stdio.h>int main(int argc,const char *argv[]){if(argc >1){ int server_socket, client_socket, longitud_cliente, puerto; puerto =atoi(argv[1]); struct sockaddr_in server;//servidor struct sockaddr_in client;//cliente server.sin_family=AF_INET;//Protocolo de internet server.sin_port=htons(puerto); server.sin_addr.s_ddr=INADDR_ANY;//Quien se puede conectarbzero(&(server.sin_zero),8);//Se requiere para usar las librerias de sockets//Socked del servido en modo escuchaif((server_socket =socket(AF_INET,SOCK_STREAM,0))){perror("No pude abrir el socket\n");return-1;}//Conectar el Socked con un puertoif(bind(server_socket,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1){perror("no pude abrir el puerto %s\n", argv[1]);return-2;}//Socked de modo escuchaif(listen(server_socket,5)==-1){perror("No pude ponerme en modo escucha\n");}//darle respuesta al cliente desde el servicor longitud_cliente =sizeof(struct sockaddr_in );//Resivir nuestro primer clienteif((client_socket =accept(server, socket,(struct sockaddr*)&client,&longitud_cliente)))==-1{printf("No pudimos aceptar una conexión\n");return-4;}//Comunicarnos con el cliente char str [INET_ADDRSTRLEN];inet_ntop(AF_INT,&(client.sin_addr), str,INET_ADDRSTRLEN);printf("se conecto un cliente desde %s:%d. Lo saludo\n", str, client.sin_port);send(client_socket,"Bienvenido a mi servidor.\n",26,0);printf("El saludo fue enviado!\n");shutdown(client_socket,2);shutdown(server_socket,2);}else{printf("por favor indique el puerto\n");return-5;}}```
Les dejo el código bien comentado por mi persona por si les faltó algo. Si tienen alguna corrección haganmela saber, yo igual ando medio perdido con tanta cosa.
//libraries with the needed definitions:#include <sys/sockets.h>#include <netinet/in.h>#include <arpa/inet.h>/*
struct sockaddr_in
{
short int sin_family;
unsigned short int sin_port;
struct in_addr sin_addr;
unsigned char sin_zero[8];
};
struct sockaddr
{
unsigned short sa_family;
char sa_data[14];
};
int socket(int domain, int type, int protocol);
int bind(int sockfd, const struct sockaddr *myaddr, int addrlen);
int listen(int s, int backlog);
int accept(int sockfd, const struct sockaddr *addr, socklen_t addrlen);
ssize_t send(int sockfd, const void *buf, size_t len, int flags);
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
int shotdown();
*/#include <string.h>int main(int argc, char const*argv[]){//the first argument will be the port of communicationif(argc >1){//the needed variables int server_socket, client_socket, longitud_cliente, puerto;//casting the argument to an integer puerto =atoi(argv[1]);//defining the n-points struct sockaddr_in server; struct sockaddr_in client;// server variables server.sin_family=AF_INET;//protocol type (TCP-IP) server.sin_port=htons(port);//the integer with the port number gets transformed to the needed structure server.sin_addr.s_addr=INDDR_ANY;//any client could get connectedbzero(&(server.sin_zero),8);//this function fulls a string with 0'sif((server_socket =socket(AF_INET,SOCK_STREAM,0))==-1)//a socket is created for the server (protocol family, specific protocol (TCP/IP), configuration (0 for automatic configuration))//if the function goes right returns a value different of -1{perror("no pude abrir el socket\n")//printed in case of opening errorreturn1;}if(bind(server_socket,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1)//the server socket is associated to a port (the scoket, a pointer to a socket address structure for the configuration, size of the structure)//if the function goes right returns a value different of -1{perror("no pude abrir el puerto %s y asociarlo con el socket\n", srgv[1]);//this could happen if the port is already opened by other applicationreturn2;}if(listen(server_socket,5)==-1)//the port now is listening for only 5 clients//if the function goes right returns a value different of -1{perror("no pude ponerme en modo escucha\n");return3;}//needed for the enxt function longitud_cliente =sizeof(struct sockaddr_in);if(client_socket =accept(server_socket,(struct sockaddr *)&client,&longitud_cliente)==-1)//accepts the first client waiting for service (the server_socket accepts the conection, a pointer to a socket address structure for the configuration, size of the structure)//if the function goes right returns a value different of -1{printf("No se pudo establecer conección con \n");return4;}//at this point the conection has been established//in order to see the client's direction... char str[INET_ADDRSTRLEN];//...transforms a direction to a string (protocol, direction to trasform, pointer to a buffer where the address is going to be saved, max size of the buffer)inet_ntop(AF_INET,&(client.sin_addr), srt,INET_ADDRSTRLEN);//it advice the client connected, his IP and portprintf("Se conectó un cliente desde la IP: %s, desde el puerto: %d\tlo saludo\n", str, client.sin_port);//send a message to the client (to who, message, size of the message, modificators bit to bit (0 for no one))send(client_socket,"Bienvenido a mi servidor.\n",26,0);//advice that the graet has been sentprintf("Saludo enviado!\n");//closing the communication(closing socket, how it gonna be closed (2 for be closed completly))shutdown(client_socket,2);shutdown(server_socket,2);}else//if the port has not been passed by the command parameter{printf("No se indicó el puerto\n");return5;}return0;}```
Woow!!! Que gran aporte crack, gracias infinitas!!!
Esto en definitiva no es parte de un curso de introducción a C, ya es un nivel intermedio o avanzado, no hay explicación previa sobre Sockets y nada de whiteboarding para una mayor claridad.
Me decepciona un poco este curso, yo sé que no se pretende asimilar todo de golpe pero ni siquiera se detiene a explicar un poco porque coloca las cosas.
no me deja utilizar la libreria socket que hago?
Qué error te lanza o que problema específicamente tienes, con tan poca información es díficil ayudarte.
¡Hola @tydi68! Siempre que tengas este tipo de errores, comparte una captura de pantalla del mensaje que te arroja la consola y copia y pega tu código en tu comentario así podemos ayudarte de mejor manera. Por otro lado te comento que la actualización de este curso saldrá en algunos días, te comparto el link por si quieres verlo.
¿Estos structs tienen una estructura predeterminada? o ¿porqué el no los define?