Bueno estoy programando en C++ y no consigo que los sockets intercanvien mensajes, es decir que envio algo y no se muestra nada por pantalla.
E probado con ponerle cout delante de recv pero no se muestra nada, aqui el codigo:
Servidor:
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int linux_socket_serv(int portNum, int bufsize = 1024)
{
int client, server;
bool isExit = false;
char buffer[bufsize];
struct sockaddr_in server_addr;
socklen_t size;
//Init socket
client = socket(AF_INET, SOCK_STREAM, 0);
if (client < 0)
{
cout << "[-] Error creando socket... " << endl;
exit(1);
}
cout << "[+] Socket creado correctamente... " << endl;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htons(INADDR_ANY);
server_addr.sin_port = htons(portNum);
//Conectando sockets
if (bind(client, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0)
{
cout << "[-] Error conectando sockets... " << endl;
exit(1);
}
size = sizeof(server_addr);
cout << "[+] Esperando clientes... " << endl;
//Esperando clientes
listen(client, 3);
//Aceptar cliente
server = accept(client, (struct sockaddr*)&server_addr, &size);
if (server < 0)
{
cout << "[-] Error aceptando cliente... " << endl;
exit(1);
}
strcpy(buffer, "Servidor conectado...");
send(server, buffer, bufsize, 0);
cout << "[+] Conectado con cliente... " << endl;
recv(server, buffer, bufsize, 0);
close(client);
return 0;
}
int main()
{
linux_socket_serv(1500,1024);
return 0;
}
y aqui el cliente:
#include <iostream>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <netdb.h>
using namespace std;
int linux_socket_clie(int portNum, char* ip, int bufsize = 1024)
{
int client, server;
bool isExit = false;
char buffer[bufsize];
struct sockaddr_in server_addr;
//Init socket
client = socket(AF_INET, SOCK_STREAM, 0);
if (client < 0)
{
cout << "[-] Error creando sockets... " << endl;
exit(1);
}
cout << "[+] Socket creado... " << endl;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(portNum);
//Conectando sockets
if (connect(client, (struct sockaddr*)&server_addr, sizeof(server_addr)) == 0)
{
cout << "[+] Conectando con el servidor... " << endl;
}
cout << recv(client, buffer, bufsize, 0);
cout << "[+] Conexion confirmada... " << endl;
cin >> buffer;
send(client, buffer, bufsize, 0);
return 0;
}
int main()
{
linux_socket_clie(1500, "127.0.0.1", 1024);
return 0;
}
El programa se queda parado en:
Servidor:
- Socket creado correctamente...
- Esperando clientes...
Cliente: