我是初學socket編程和讀Linux網絡編程的書。我決定實現本書中所示的客戶端 - 服務器連接。服務器程序在Ubuntu 14.04機器上運行,客戶機代碼從Mac機器運行。該服務器代碼如下套接字連接失敗
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <string.h>
const char message[] = "hello, world\n";
int main()
{
int sock = 0;
int port = 0;
sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1)
fprintf(stderr, "failed\n");
else
printf("connection is establisshed\n");
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = 3500;
int status = bind(sock, (struct sockaddr*) &server, sizeof(server));
if (status == 0)
printf("connection completed\n");
else
printf("problem is encountered\n");
status = listen(sock, 5);
if (status == 0)
printf("app is ready to work\n");
else
{
printf("connection is failed\n");
return 0;
}
while (1)
{
struct sockaddr_in client = { 0 };
int sclient = 0;
int len = sizeof(client);
int childSocket = accept(sock, (struct sockaddr*) &client, &len);
if (childSocket == -1)
{
printf("cannot accept connection\n");
close(sock);
break;
}
write(childSocket, message, strlen(message));
close(childSocket);
}
return 0;
}
至於客戶端我寫了下面的代碼
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
int main(int argc, char* argv[])
{
int sock = 0;
int port = 0;
struct sockaddr_in servaddr;
sock = socket(AF_INET, SOCK_STREAM, 0);
int status = 0;
char buffer[256] = "";
if (sock == -1)
{
printf("could not establish connection\n");
exit(1);
}
port = 3500;
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
servaddr.sin_port = htons(port);
status = connect(sock, (struct sockaddr*) &servaddr, sizeof(servaddr));
if (status == 0)
printf("connection is established successfully\n");
else
{
printf("could not run the app\n");
exit(1);
}
status = read(sock, buffer, sizeof(buffer));
if (status > 0)
printf("%d: %s", status, buffer);
close(sock);
return 0;
}
要獲得客戶機的IP地址,我運行ifconfig從終端的獲取inet_addr 192.168.1.165值。現在,當我將該地址字符串作爲命令行參數傳遞時,我得到的消息是該應用程序未運行消息。據我所知,地址有問題。那麼問題是什麼? 在此先感謝
建議使用'PERROR()'以日誌錯誤消息。它提供了更詳細的錯誤信息。檢測到錯誤後立即調用它,之前不要調用任何其他函數。 – alk
「我收到消息,該應用沒有運行消息」。不,你不知道。你的應用程序不會打印這樣的消息,如果它沒有,它應該沒有:它應該已經打印了'errno',或者'strerror()'的結果,最簡單的使用'perror()「。澄清你的題。 – EJP