1
I’m learning to program sockets but I’m having problems when it comes to exchanging messages between the client and the server, the two codes work as "should" only the problem is time to send a message and receive.
cpp client.
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <iostream>
#include <errno.h>
struct sockaddr_in server;
#define buffer 200
int main(){
std::string menssagm;
int clientfd=(socket(AF_INET, SOCK_STREAM, IPPROTO_TCP));
if(clientfd==-1){
perror("socket");
std::cout << "Falha\n";
}else{
std::cout << "Ok...\n";
}
server.sin_family=AF_INET;
server.sin_port=htons(2000);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
int serverfd=(connect(clientfd, (struct sockaddr*)&server, sizeof(server)));
if(serverfd==-1){
std::cout << "Erro...\n";
perror("connect");
}else{
std::cout << "Conexão estabelecida com sucesso\n";
if((recv(serverfd,(void*)menssagm.c_str(), buffer, 0)==-1)){
std::cout << "Erro ao receber menssagem\n";
perror("recv");
}else{
std::cout << "Menssagem recebida\n";
std::cout << menssagm << "\n";
}
if((send(serverfd, "script kiddie", buffer, 0)==-1)){
std::cout << "Erro ao enviar menssagem\n";
perror("send");
}else{
std::cout << "Menssagem enviada";
}
}
}
cpp server.
#include <iostream>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
struct sockaddr_in local;
struct sockaddr_in remoto;
std::string hello="Hello";
std::string word;
int main(){
int localFd=((socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)));
local.sin_family=AF_INET;
local.sin_port=htons(2000);
local.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(localFd,(struct sockaddr*)&local, sizeof(local));
listen(localFd,1);
int remotoFd;
socklen_t len=sizeof(remoto);
if((remotoFd=accept(localFd, (struct sockaddr*)&remoto, &len))==-1){
std::cout << "Erro...\n";
}else{
std::cout << "Conexão recebida com sucesso\n";
send(remotoFd, hello.c_str(), 50, 0);
recv(remotoFd, (void*)word.c_str(), 50, 0);
std::cout << word << "\n";
}
}
The return of function perror is:
recv(): Socket operation on non-socket
send(): Socket operation on non-socket
Because you gave close(...) and shutdown(..) only in the client descriptor?
– user83187
@Khyser: Experimentally, the server code is inside an infinite loop
while(1){}
. The server code will NEVER reach thereturn 0
ofmain()
, if there was aclose()
and ashutdown()
there, they also would never be hit.– Lacobus
What is the difference between shutdown and close?
– user83187
shutdown()
changes the state ofsocket
, blocking the sending and/or receiving of data in all processes that share it, however, it does not free the memory allocated by the descriptor. Alreadyclose()
blocks the sending and receiving of data and releases the memory allocated by the descriptor only of the process responsible for the call. - https://stackoverflow.com/questions/4160347/close-vs-shutdown-socket– Lacobus