我用C \ C ++编写了一个客户端,并向正在使用nc -l -p 6666
进行监听的本地计算机发送了一条消息。
发送邮件后,本地主机上的nc
没有任何问题。
我想问题出在我的代码中,但是我不确定哪一行。
为什么我没有收到任何与nc
相关的消息?
代码:
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[]) {
//http://www.linuxhowtos.org/C_C++/socket.htm
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
const char ip[] = "127.0.0.1";
char buffer[256];
portno = atoi("6666");
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
/*
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,
server->h_length);
*/
inet_aton(ip, &serv_addr.sin_addr);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0){
error("ERROR connecting");
}
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
close(sockfd);
return(0);
}
答案 0 :(得分:3)
There are three parts to a sockaddr_in
:
inet_aton
(assuming the call succeeded; best add some error checking!)serv_addr.sin_port = htons(portno);
AF_INET
in your case but, oops, you commented this out!Everything else looks fine.