我正在運行linux mint,並在命令終端中輸入了一些命令來連接到本地主機,但它一直說連接失敗。無法連接到本地主機
這是我鍵入:
echo "echo test" | ./<my executable> localhost <port #>
這裏是我的連接代碼:
int r = connect(sock, addrList->ai_addr, addrList->ai_addrlen);
if (r < 0) {
printf("Connection failed\n");
exit(1);
}
這裏是全碼:
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Invalid arguments\n");
exit(1);
}
char *serverIP = argv[1]; /*Server hostname*/
char *portNumber = argv[2]; /*Port Number*/
void *numericAddress;
char addrBuffer[INET6_ADDRSTRLEN];
in_port_t port;
char buffer_stdin[65535];
char buffer_stdout[65535];
int bytes_read = 0;
int bytes_written = 0;
/*getting integral number of string representation of port number*/
in_port_t servPort = atoi(argv[2]);
/*------------------get binary number of hostname-----------------*/
struct addrinfo addrCriteria;
memset(&addrCriteria, 0, sizeof(addrCriteria));
addrCriteria.ai_family = AF_INET;
addrCriteria.ai_socktype = SOCK_STREAM;
addrCriteria.ai_protocol = IPPROTO_TCP;
struct addrinfo *addrList;
int rtnVal = getaddrinfo(serverIP, portNumber, &addrCriteria, &addrList);
if (rtnVal != 0) {
printf("getaddrinfo() failed\n");
exit(1);
}
numericAddress = &((struct sockaddr_in *) (addrList->ai_addr))->sin_addr;
/*Converting port to binary*/
((struct sockaddr_in *)(addrList->ai_addr))->sin_port = htons(servPort);
/*----------------------------------------------------------------*/
inet_ntop(addrList->ai_addr->sa_family, numericAddress, addrBuffer, sizeof(addrBuffer));
printf("IP ADDRESS: %s\n", addrBuffer);
/*Creating socket*/
int sock = socket(AF_INET,SOCK_STREAM, IPPROTO_TCP);
if (sock < 0) {
printf("error creating socket\n");
exit(1);
}
/*Establish connection to the echo server*/
int r = connect(sock, addrList->ai_addr, addrList->ai_addrlen);
if (r < 0) {
perror("Connection failed\n");
exit(1);
}
/*Reading from stdin and writing to socket until stdin ends
bytes_read = read(0, buffer_stdin, sizeof(buffer_stdin));
write(sock, buffer_stdin, bytes_read);*/
while ((bytes_read = read(0, buffer_stdin, sizeof(buffer_stdin)-1)) > 0) {
write(sock, buffer_stdin, bytes_read);
}
/*Shutting down write end of socket*/
int r_shutdown = shutdown(sock, SHUT_WR);
if (r_shutdown < 0) {
printf("Shutting down write end of socket failed\n");
exit(1);
}
/*Reading from socket and writing to stdout until socket ends*/
while ((bytes_read = read(sock, buffer_stdout, sizeof(buffer_stdout)-1)) > 0) {
write(1, buffer_stdout, bytes_read);
}
close(sock);
exit(0);
}
我是否需要安裝東西連接到本地主機?
感謝
編輯:確定這裏是一個更新:
首先我鍵入指令終端的:chmod a + X exe文件(其中EXE是我們的UDP服務器) 然後我輸入:./ exe例如./exe 2525 然後我輸入:echo「echo test」| ./ localhost
但是,如果發生這種情況,終端不會返回「回聲測試」,就像它正在等待用戶輸入,或者如果它陷入無限循環一樣。
您還沒有表現出我們足夠的代碼。此外,使用'perror(「連接失敗\ n」);'而不是'printf(「連接失敗\ n」);'看看爲什麼連接失敗 – 2014-09-12 18:22:54
好吧,我會嘗試 – umdcoder 2014-09-12 18:28:11
它說:「連接拒絕」。我將發佈我的代碼的其餘部分 – umdcoder 2014-09-12 18:29:05