我已經閱讀了很多與C網絡連接的例子,我被卡住了。我可以看到帶有SYN標誌的TCP數據包在線上(使用wireshark),但接收端(我爲測試目的而設置了一個虛擬機)沒有發回任何內容,甚至沒有發送RST。TCP:建立一個TCP連接
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <strings.h>
int establish_tcp(int port) {
char *ip = "10.0.2.15"; /* Virtual Machine */
struct sockaddr_in sockaddrin;
struct hostent *host;
int sock;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1) {
fprintf(stderr, "Socket Error\n");
exit(1);
}
sockaddrin.sin_family = AF_INET;
host = gethostbyname(ip);
if(host == NULL) {
fprintf(stderr, "%s unknown host.\n", ip);
exit(2);
}
/* copies the internet address into the struct */
bcopy(host->h_addr, &sockaddrin.sin_addr, host->h_length);
/* specify port (used by TCP a layer above */
sockaddrin.sin_port = port;
/* try to connect */
return connect(sock, (struct sockaddr*) &sockaddrin, sizeof(struct sockaddr_in));
}
int main(void) {
printf("status: %i\n", establish_tcp(80));
return 0;
}
直到數據包超時並且返回-1作爲狀態碼需要一段時間。目標機器如何不發送回覆?我忽視了什麼?
我想我已經想通了,這是不是一個設置問題。我正在運行Ubuntu 12.04。虛擬機是Debian Wheezy,我用ifconfig
檢查它的IP。我試過如果機器可用telnet
。
爲了避免可能與Virtual Box相關的問題,我嘗試用Google的IP替換IP,產生相同的結果。
這更是一個問題,關於你的網絡設置高於約編程本身。用有關您測試環境的詳細信息更新問題。很可能您嘗試連接到無法訪問的IP地址,並且可能有很多原因。 –
可能你會大聲地使用諸如telnet或netcat先連接到這個IP /端口。 –