Enviado em 15/10/2018 - 22:15h
Olá, estou tendo problemas para converter network byte order para host byte order com a função ntohs(). Eu não entendi o porque da conversão está dando problemas, pois a função que estou usando para converter host byte order para network byte order é a htons(), o que tecnicamente deveria dar certo, pois ambas as funções trabalham com unsigned short.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(void){
struct sockaddr_in addr, remoteAddr;
socklen_t socklen=sizeof(struct sockaddr_in);
int sockfd=socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(sockfd<0){
perror("ERROR (SOCKET)");
exit(1);
}
addr.sin_family=AF_INET;
addr.sin_port=htons(9009);
addr.sin_addr.s_addr=inet_addr("127.0.0.1");
if(bind(sockfd, (const struct sockaddr*)&addr, socklen)<0){
perror("ERROR (BIND)");
exit(1);
}
if(listen(sockfd, 1)<0){
perror("ERROR (LISTEN)");
exit(1);
}
int csockfd=accept(sockfd, (struct sockaddr*)&remoteAddr, &socklen);
if(csockfd<0){
perror("ERROR (BIND)");
}else{
printf("\nConnected successfully with %s:%hu\n\n",
inet_ntoa(remoteAddr.sin_addr), ntohs(remoteAddr.sin_port));
if(send(csockfd, "REAL MOTHERFUCKIN G'S", 22, 1)<0){
perror("ERROR (SEND)");
}
}
close(csockfd);
close(sockfd);
return 0;
}
Zhokhaidooo@Zhokhaidooo:~/Desktop/PrograshitoPpkX$ gcc -Wall server.c -o server
Zhokhaidooo@Zhokhaidooo:~/Desktop/PrograshitoPpkX$ ./server
Connected successfully with 127.0.0.1:42798
Zhokhaidooo@Zhokhaidooo:~/Desktop/PrograshitoPpkX$ nc 127.0.0.1 9009
REAL MOTHERFUCKIN G'S
Atualizando o Passado: Linux no Lenovo G460 em 2025
aaPanel - Um Painel de Hospedagem Gratuito e Poderoso
O macete do Warsaw no Linux Mint e cia
Visualizar arquivos em formato markdown (ex.: README.md) pelo terminal
Dando - teoricamente - um gás no Gnome-Shell do Arch Linux
Como instalar o Google Cloud CLI no Ubuntu/Debian
Mantenha seu Sistema Leve e Rápido com a Limpeza do APT!
Procurando vídeos de YouTube pelo terminal e assistindo via mpv (2025)
Jogos baixados na Central de Aplicativos mas que não abrem (1)
debian com wayland, configuracao de teclado. Mudou Tudo! [RESOLVIDO] (1)
Iinstalar o Scanner Kodak i940 no Linux Mint 19/20? (3)
Pastas da raiz foram para a área de trabalho [RESOLVIDO] (11)