Todo me funcionó perfecto. Está genial. Voy a intentarlo con máquinas remotas.
Por cierto, ese comando de vim está genial! Platzi debería considerar hacer un curso de vim, es un editor muuy completo :O
Si!!!! Por favor un curso de Vim.
no se imagina por la cantidad de problemas para que esto funcionara y aunque el código del profe en linux es parecido al que yo escribí en windows realmente la sufri ya que casi no hay mucha info al menos en español pero he aquí vivito y coleando
{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;}
/*************************CLIENTE********************************/#include <winsock2.h>#include <windows.h>#include <stdio.h>int main(int argc, char ** argv){if(argc !=3){printf(" introduce: la IP del Cliente y el PUERTO del servidor");return-1;}WSADATA wsaData ={0};SOCKET socket_cliente;SOCKADDR_INServidor={0};WSAStartup(MAKEWORD(2,2),&wsaData);printf("abriendo el socket del cliente\n");if((socket_cliente =socket(AF_INET,SOCK_STREAM,IPPROTO_TCP))==SOCKET_ERROR){printf("no se pudo abrir el socket\n");return-2;}Servidor.sin_family=AF_INET;Servidor.sin_port=htons((WORD)atoi( argv[2]));Servidor.sin_addr.s_addr=inet_addr(argv[1]);printf("conectando %s con %s\n",argv[1],argv[2]);if(connect(socket_cliente,(SOCKADDR*)&Servidor,sizeof(Servidor))==SOCKET_ERROR){printf("no pude conectarma al servidor\n");return-3;}printf("Resibiendo...\n"); int Envio; char buff [100];if((Envio=recv(socket_cliente,buff,100,0))==-1){printf("Error en la lectura\n");return-4;} buff[Envio]='\0';printf("Elservidor envio el mensaje : '%s'\n",buff);closesocket(socket_cliente);WSACleanup();return0;}
Yo espero entenderlo con los próximos que tomare mas adelante y volvere para entender realmente este
Fue muy complicado seguir el paso, felicitaciones por haberlo logrado
El mejor ejercicio del curso! 💪🏽
Como lo prometido es deuda logre hacer una comunicación entre un programa corriendo en linux con un programa corriendo en windows muajajaj el mundo sera mio XD
;
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>#include <stdlib.h>#include <stdio.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, port;//casting the argument to an integer port =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=INADDR_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{printf("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{printf("no pude abrir el puerto %s y asociarlo con el socket\n", argv[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{printf("no pude ponerme en modo escucha\n");return3;}//accepting clientsprintf("Todo listo! Aceptando clientes...\n"); 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), str,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, 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 pedilecto, sublime y elegante servidor.",55,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;}
CLIENTE
//libraries with the needed definitions:#include <sys/socket.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>#include <stdlib.h>#include <stdio.h>int main(int argc, char const*argv[]){//the first argument will be the server IP//the second argument will be the communication portif(argc >2){//a string that holds the server IPconst char *ip;//a socket for the client, the amount of bytes that will be recieved or sent, the port int client_socket, numbytes, port; char buff[100];//pff it's a buffer//giving the respective values to the IP and port ip = argv[1]; port =atoi(argv[2]);//server information struct sockaddr_in server;if(inet_pton(AF_INET, ip,&server.sin_addr)<=0)//convert the argument to an IP address (protocol family, specific protocol (TCP/IP), configuration (0 for automatic configuration))////if the function goes right returns a value different of -1{printf("la IP %s no es valida\n", ip);return1;}//creating the client socketprintf("Abriendo el socket del cliente...\n");if((client_socket =socket(AF_INET,SOCK_STREAM,0))==-1)//a socket is created for the client (protocol family, specific protocol (TCP/IP), configuration (0 for automatic configuration))//if the function goes right returns a value different of -1{printf("no pude abrir el socket\n");return2;}//server variables to especify which server to connect to 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 structurebzero(&(server.sin_zero),8);//this function fulls a string with 0's//trying to get connectedprintf("Conectando a IP: %s, desde el puerto: %d\n", ip, port);if(connect(client_socket,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1)//the client socket is connecting to a server (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{printf("no pude conectarme al servidor\n");return3;}//recieving message and printing itprintf("Recibiendo...\n");////////////////if((numbytes =recv(client_socket, buff,100,0))==-1)//recieve a message from the server (///////////to who, a pointer to the buffer where the message is gonna be saved, size of the buffer, modificators bit to bit (0 for no one))//if the function goes right returns a value different of -1{printf("no se recibio el mensaje\n");return4;} buff[numbytes]='\0';printf("El servidor envia:\t'%s'\n", buff);//closing the communication(closing socket, how it gonna be closed (2 for be closed completly))shutdown(client_socket,2);}else//if the port has not been passed by the command parameter{printf("No se indico la IP o el puerto\n");return5;}return0;}```
Todo está bastante bien comentado en inglés asi que espero les sirva.
No encuentro el motivo por el cual mi programa cliente, no conecta con el servidor, valide el codigo y no encuetro el error :|
Alguien puede darme una idea ?
al momento de correr el programa me va todo bien pero el servidor no envia el mensaje (bienvenido a mi servidor) a mi cliente
alguien que pueda encontrar un error en mi codigo
ESTE ES EL CODIGO DE MI SERVIDOR
#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <string.h>#include <stdio.h>#include <stdlib.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; struct sockaddr_in client; server.sin_family=AF_INET; server.sin_port=htons( puerto ); server.sin_addr.s_addr=INADDR_ANY;bzero(&(server.sin_zero),8);if(( server_socket =socket(AF_INET,SOCK_STREAM,0))==-1){printf("No pude abrir el socket\n");return-1;}if(bind( server_socket,(struct sockaddr *)&server,sizeof(struct sockaddr))==-1){printf("No puede abrir el puerto %s\n", argv[1]);return-2;}if(listen( server_socket,5)==-1){printf("No pude ponerme en modo escucha\n");return-3;} longitud_cliente =sizeof( struct sockaddr );printf("esperando clientes.....\n");if(( client_socket ==accept( server_socket,(struct sockaddr*)&client,&longitud_cliente ))==-1){printf("No pudimos aceptar una conexion\n");return-4;} char str[INET_ADDRSTRLEN];inet_ntop(AF_INET,&(client.sin_addr), str,INET_ADDRSTRLEN);printf("se conecto el cliente desde %s:%d. lo saludo\n", str, client.sin_port);send( client_socket,"Bienvenido a mi servidor.\n",26,0);printf("saludo enviado\n");shutdown( client_socket,2);shutdown( server_socket,2);}else{printf("Por favor indique el puerto\n");return-5;}}
**este es el codigo de mi cliente **
#include <stdlib.h>#include <stdio.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>int main(int argc,const char * argv[]){if( argc >2){const char *ip; int client_socket, numbytes, puerto; char buff[100]; puerto =atoi( argv[2]); ip = argv[1]; struct sockaddr_in server;if(inet_pton(AF_INET,argv[1],&server.sin_addr)<=0){printf("la ip %s no es valida\n", ip );return-1;}printf("abriendo el socket\n");if(( client_socket =socket(AF_INET,SOCK_STREAM,0))==-1){printf("No pude abrir el socket\n");return-2;} server.sin_family=AF_INET; server.sin_port=htons( puerto );bzero(&(server.sin_zero),8);printf("conectando a %s:%s\n", argv[1], argv[2]);if(connect( client_socket,(struct sockaddr *)&server,sizeof( struct sockaddr ))==-1){printf("No pude conectarme con el servidor\n");return-3;}printf("Recibiendo...\n");if(( numbytes =recv( client_socket, buff,100,0))==-1){printf("Error en la lectura\n");return-4;} buff[numbytes]='\0';printf("El servidor envio el mensaje '%s'\n", buff );shutdown( client_socket,2);}else{printf("Por favor, indique el ip del servidor y puerto\n");return-5;}}
en la terminal de mi cliente me sale esto
abriendo el socket
conectando a 127.0.0.1:9087Recibiendo...El servidor envio el mensaje ''
Muchos de estos errores ya los había visto anteriormente, pero por dar por hecho lo que el profesor decía se colaron en el código.¡Nunca está demás cuestionarse!!
Gracias!
Saludos,
Muchas gracias por el curso. Respecto al modulo de comunicación entre procesos, en windows 10 falta explicación sobre algunos archivo que se deben instalar, pues las librerias de sockets no las encuentra el programa, y esto hace que falle la compilación
hola disculpe la molestia hay que descargar algun programa o librerias para que funcione el socket
yo lo resolví con windows.h y winsock2.h así que pueden checar el codigo que hice en cada clase lo deje todo ahi
Excelente aplicación de sockets funciono a la perfección, muchas gracias.
Esta tarea de revisar el código me gusta yo lo hago siempre antes de compilarlo.
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>int main(int argc, char const*argv[]){// Direccion ip del server, puertoif( argc >2){const char *ip; int client_socket, numbytes, puerto; char buff[100]; ip = argv[1]; puerto =atoi( argv[2]);// Server al que nos queremos conectar struct sockaddr_in server;// Convertir el argumento a direccion ipif(inet_pton(AF_INET, ip,&server.sin_addr)<=0){printf("La ip %s no es valida\n", ip);return-1;}printf("Abriendo el socket");// Abrir el socket del clienteif(( client_socket =socket(AF_INET,SOCK_STREAM,0))==-1){printf("No pude abrir el socket\n");return-2;}// A que server nos vamos a conectar? server.sin_family=AF_INET; server.sin_port=htons( puerto );// COnvertir a estrcturabzero(&(server.sin_zero),8);// Intentar la conexionprintf("Conectando a %s:%d", ip, puerto);if(connect( client_socket,(struct sockaddr *)&server,sizeof( struct sockaddr ))==-1){printf("No pude conectarme al servidor\n");return-3;}// Recibir info del serverprintf("Recibiendo...\n");if(( numbytes =recv( client_socket, buff,100,0))==-1){printf("Error en la lectura");return-4;}// Termina buff[numbytes]='\0';printf("El servidor envio el mensaje:%s\n", buff);shutdown( client_socket,2);}// EL usuario no ingreso el puerto por la linea de comandoselse{printf("Porfavor indique ip del server y el puerto\n");return-5;}return0;}
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/socket.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))==-1){printf("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){printf("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){printf("No pude ponerme en modo escucha");return-3;} longitud_cliente =sizeof( struct sockaddr_in );printf("Espernaod clientes...\n");// 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;}
Wow GENIAL!
Funciono en el WSL Linux de windows
fue interesante el curso en general, deberia haber una mayor cantidad de cursos del profe Mauro, ya que es un buen profesor (desde mi punto de vista).
en mi caso lo estuve haciendo en MAC y solo me saltó un error como este:
warning: passing 'int *' to parameter of type 'socklen_t *' (aka 'unsigned int *') converts between pointers to integer types with different sign [-Wpointer-sign]
if((client_socket = accept(server_socket, (struct sockaddr *) &client, &longitud_cliente)) == -1) {
^~~~~~~~~~~~~~~~~
/Library/Developer/CommandLineTools/SDKs/MacOSX10.14.sdk/usr/include/sys/socket.h:686:73: note: passing argument to parameter here
int accept(int, struct sockaddr * __restrict, socklen_t * __restrict)
La solución fue declarar la variable longitud_cliente como unsigned int: