2012-08-01 4 views
0

그러나 동일한 Ipaddress를 사용하여 클라이언트 코드를 통해 서버에 연결하면 연결이 수신됩니다. connect() failed : Connection refused. 나는 getsockname을 통해 서버 IPADDRESS를(). 내가받은 여기서 ipaddress는내 클라이언트 서버 코드에서 ifconfig를 통해 얻은 Ipaddress를 사용하여 서버에 텔넷을 연결할 수 있습니까?

주소입니다 확인하고 싶다고 '0.0.0.0:9000은' 나는이 내가 오라클 가상 상자 환경 (우분투) 를 사용하여 biggner 프로그래머입니다 사용 서버에 연결하기 위해 클라이언트에 전달할 ipaddress를 지정하십시오. 사용법 : ./ 사용법 :. < "문자열"> 기본적으로 에코 서버를 만들려고합니다. 미리 감사드립니다. 클라이언트 코드 : 사용법 #include "Practical.h"

int main(int argc, char *argv[]) { 



if (argc < 3 || argc > 4) // Test for correct number of arguments 
    DieWithUserMessage("Parameter(s)", 
     "<Server Address> <Echo Word> [<Server Port>]"); 

    char *servIP = argv[1];  // First arg: server IP address (dotted quad) 
    char *echoString = argv[2]; // Second arg: string to echo 

    // Third arg (optional): server port (numeric). 7 is well-known echo port 
    in_port_t servPort = (argc == 4) ? atoi(argv[3]) : 7; 

    // Create a reliable, stream socket using TCP 
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 
    if (sock < 0) 
    DieWithSystemMessage("socket() failed"); 

    // Construct the server address structure 
    struct sockaddr_in servAddr;   // Server address 
    memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure 
    servAddr.sin_family = AF_INET;   // IPv4 address family 
    // Convert address 
    int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr); 
    if (rtnVal == 0) 
    DieWithUserMessage("inet_pton() failed", "invalid address string"); 
    else if (rtnVal < 0) 
    DieWithSystemMessage("inet_pton() failed"); 
    servAddr.sin_port = htons(servPort); // Server port 
    printf ("Hello"); 

    // Establish the connection to the echo server 
    if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) 
    DieWithSystemMessage("connect() failed"); 

    size_t echoStringLen = strlen(echoString); // Determine input length 

    // Send the string to the server 
    ssize_t numBytes = send(sock, echoString, echoStringLen, 0); 
    if (numBytes < 0) 
    DieWithSystemMessage("send() failed"); 
    else if (numBytes != echoStringLen) 
    DieWithUserMessage("send()", "sent unexpected number of bytes"); 

    // Receive the same string back from the server 
    unsigned int totalBytesRcvd = 0; // Count of total bytes received 
    fputs("Received: ", stdout);  // Setup to print the echoed string 
    while (totalBytesRcvd < echoStringLen) { 
    char buffer[BUFSIZE]; // I/O buffer 
    /* Receive up to the buffer size (minus 1 to leave space for 
    a null terminator) bytes from the sender */ 
    numBytes = recv(sock, buffer, BUFSIZE - 1, 0); 
    if (numBytes < 0) 
     DieWithSystemMessage("recv() failed"); 
    else if (numBytes == 0) 
     DieWithUserMessage("recv()", "connection closed prematurely"); 
    totalBytesRcvd += numBytes; // Keep tally of total bytes 
    buffer[numBytes] = '\0'; // Terminate the string! 
    fputs(buffer, stdout);  // Print the echo buffer 
    } 

    fputc('\n', stdout); // Print a final linefeed 

    close(sock); 
    exit(0); 
} 

Server Code : 
#define BUFSIZE 512 
void HandleTCPClient(int clntSocket) { 
    char buffer[BUFSIZE]; // Buffer for echo string 

    // Receive message from client 
    ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0); 
    if (numBytesRcvd < 0) 
    printf("recv() failed"); 

    // Send received string and receive again until end of stream 
    while (numBytesRcvd > 0) { // 0 indicates end of stream 
    // Echo message back to client 
    ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0); 
    if (numBytesSent < 0) 
     printf("send() failed"); 
    else if (numBytesSent != numBytesRcvd) 
     printf("send()", "sent unexpected number of bytes"); 

    // See if there is more data to receive 
    numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0); 
    if (numBytesRcvd < 0) 
     printf("recv() failed"); 
    } 

    close(clntSocket); // Close client socket 
} 
static const int MAXPENDING = 5; 
int main(int argc, char *argv[]) { 

    if (argc != 2) 
    { 
    printf ("Parameters , <Server Port required >"); 
    } 
    in_port_t servPort = atoi(argv[1]); 
    int servSock; // Socket descriptor for server 
    if ((servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
    { 
    printf ("Socket Failed "); 
    exit (1); 
    } 
    struct sockaddr_in servAddr;     // Local address 
    memset(&servAddr, 0, sizeof(servAddr));  // Zero out structure 
    servAddr.sin_family = AF_INET;    // IPv4 address family 
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface 
    servAddr.sin_port = htons(servPort);   // Local port 

    // Bind to the local address 
    if (bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0) 
    { 
    printf ("Bind Failed "); 
    exit (1); 
    } 
    // Mark the socket so it will listen for incoming connections 
    if (listen(servSock, MAXPENDING) < 0) 
    printf("listen() failed"); 
    for (;;) { // Run forever 
    struct sockaddr_in clntAddr; // Client address 
    // Set length of client address structure (in-out parameter) 
    socklen_t clntAddrLen = sizeof(clntAddr); 

    // Wait for a client to connect 
    int clntSock = accept(servSock, (struct sockaddr *) &clntAddr, &clntAddrLen); 
    if (clntSock < 0) 
     printf ("accept() failed"); 

    // clntSock is connected to a client! 

    char clntName[INET_ADDRSTRLEN]; // String to contain client address 
    if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clntName, 
     sizeof(clntName)) != NULL) 
     printf("Handling client %s/%d\n", clntName, ntohs(clntAddr.sin_port)); 
    else 
     puts("Unable to get client address"); 

    HandleTCPClient(clntSock); 
    } 
    // NOT REACHED 
} 

Code is not mine I have Copied for Practice 
+0

'0.0.0.0 : 9000'은 유효한 IP 주소가 아닙니다. ifconfig 출력을 서버에 표시 할 수 있습니까? – Konerak

+0

당신의 시나리오에는 너무 많은 미지가있어 지능적이고 간결한 대답을 할 수 없습니다. 가상 머신에 접근 할 수 있는지 확인하고, 서버에서 바인드/수락을 수행하는 코드를 보여주고, 그 정보를 추가하기 위해 글을 편집하십시오. – tbert

답변

1

이 작동합니다 :

서버 코드 :

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <unistd.h> 
#include <arpa/inet.h> 
#include <string.h> 

#define BUFSIZE 512 
void HandleTCPClient(int clntSocket) { 
    char buffer[BUFSIZE]; // Buffer for echo string 

    // Receive message from client 
    ssize_t numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0); 
    if (numBytesRcvd < 0) 
    printf("recv() failed"); 

    // Send received string and receive again until end of stream 
    while (numBytesRcvd > 0) { // 0 indicates end of stream 
    // Echo message back to client 
    ssize_t numBytesSent = send(clntSocket, buffer, numBytesRcvd, 0); 
    if (numBytesSent < 0) 
     printf("send() failed"); 
    else if (numBytesSent != numBytesRcvd) 
     printf("send(), sent unexpected number of bytes"); 

    // See if there is more data to receive 
    numBytesRcvd = recv(clntSocket, buffer, BUFSIZE, 0); 
    if (numBytesRcvd < 0) 
     printf("recv() failed"); 
    } 

    close(clntSocket); // Close client socket 
} 
static const int MAXPENDING = 5; 
int main(int argc, char *argv[]) { 

    if (argc != 2) 
    { 
    printf ("Parameters , <Server Port required >"); 
    } 
    in_port_t servPort = atoi(argv[1]); 
    int servSock; // Socket descriptor for server 
    if ((servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) 
    { 
    printf ("Socket Failed "); 
    exit (1); 
    } 
    struct sockaddr_in servAddr;     // Local address 
    memset(&servAddr, 0, sizeof(servAddr));  // Zero out structure 
    servAddr.sin_family = AF_INET;    // IPv4 address family 
    servAddr.sin_addr.s_addr = htonl(INADDR_ANY); // Any incoming interface 
    servAddr.sin_port = htons(servPort);   // Local port 

    // Bind to the local address 
    if (bind(servSock, (struct sockaddr*) &servAddr, sizeof(servAddr)) < 0) 
    { 
    printf ("Bind Failed "); 
    exit (1); 
    } 
    // Mark the socket so it will listen for incoming connections 
    if (listen(servSock, MAXPENDING) < 0) 
    printf("listen() failed"); 
    for (;;) { // Run forever 
    struct sockaddr_in clntAddr; // Client address 
    // Set length of client address structure (in-out parameter) 
    socklen_t clntAddrLen = sizeof(clntAddr); 

    // Wait for a client to connect 
    int clntSock = accept(servSock, (struct sockaddr *) &clntAddr, &clntAddrLen); 
    if (clntSock < 0) 
     printf ("accept() failed"); 

    // clntSock is connected to a client! 

    char clntName[INET_ADDRSTRLEN]; // String to contain client address 
    if (inet_ntop(AF_INET, &clntAddr.sin_addr.s_addr, clntName, 
     sizeof(clntName)) != NULL) 
     printf("Handling client %s/%d\n", clntName, ntohs(clntAddr.sin_port)); 
    else 
     puts("Unable to get client address"); 

    HandleTCPClient(clntSock); 
    } 
    // NOT REACHED 
} 

클라이언트 코드 :

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <unistd.h> 
#include <arpa/inet.h> 
#include <string.h> 

#define BUFSIZE 512 

int main(int argc, char *argv[]) { 

if (argc < 3 || argc > 4) // Test for correct number of arguments 
{ 
    fprintf(stderr, "Parameter(s), <Server Address> <Echo Word> [<Server Port>]\n"); 
    exit(EXIT_FAILURE); 
} 

    char *servIP = argv[1];  // First arg: server IP address (dotted quad) 
    char *echoString = argv[2]; // Second arg: string to echo 

    // Third arg (optional): server port (numeric). 7 is well-known echo port 
    in_port_t servPort = (argc == 4) ? atoi(argv[3]) : 7; 

    // Create a reliable, stream socket using TCP 
    int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 
    if (sock < 0) 
    { 
    fprintf(stderr, "socket() failed\n"); 
    exit(EXIT_FAILURE); 
    } 

    // Construct the server address structure 
    struct sockaddr_in servAddr;   // Server address 
    memset(&servAddr, 0, sizeof(servAddr)); // Zero out structure 
    servAddr.sin_family = AF_INET;   // IPv4 address family 
    // Convert address 
    int rtnVal = inet_pton(AF_INET, servIP, &servAddr.sin_addr.s_addr); 
    if (rtnVal == 0) 
    { 
    fprintf(stderr, "inet_pton() failed, invalid address string\n"); 
    exit(EXIT_FAILURE); 
    } 
    else if (rtnVal < 0) 
    { 
    fprintf(stderr, "inet_pton() failed\n"); 
    exit(EXIT_FAILURE); 
    } 
    servAddr.sin_port = htons(servPort); // Server port 
    printf ("Hello"); 

    // Establish the connection to the echo server 
    if (connect(sock, (struct sockaddr *) &servAddr, sizeof(servAddr)) < 0) 
    fprintf(stderr, "connect() failed\n"); 

    size_t echoStringLen = strlen(echoString); // Determine input length 
    // Send the string to the server 
    ssize_t numBytes = send(sock, echoString, echoStringLen, 0); 
    if (numBytes < 0) 
    { 
    fprintf(stderr, "send() failed\n"); 
    exit(EXIT_FAILURE); 
    } 
    else if (numBytes != echoStringLen) 
    { 
    fprintf(stderr, "send(), sent unexpected number of bytes\n"); 
    exit(EXIT_FAILURE); 
    } 

    // Receive the same string back from the server 
    unsigned int totalBytesRcvd = 0; // Count of total bytes received 
    fputs("Received: ", stdout);  // Setup to print the echoed string 
    while (totalBytesRcvd < echoStringLen) { 
    char buffer[BUFSIZE]; // I/O buffer 
    /* Receive up to the buffer size (minus 1 to leave space for 
    a null terminator) bytes from the sender */ 
    numBytes = recv(sock, buffer, BUFSIZE - 1, 0); 
    if (numBytes < 0) 
    { 
     fprintf(stderr, "recv() failed\n"); 
     exit(EXIT_FAILURE); 
    } 
    else if (numBytes == 0) 
    { 
     fprintf(stderr, "recv(), connection closed prematurely\n"); 
     exit(EXIT_FAILURE); 
    } 
    totalBytesRcvd += numBytes; // Keep tally of total bytes 
    buffer[numBytes] = '\0'; // Terminate the string! 
    fputs(buffer, stdout);  // Print the echo buffer 
    } 

    fputc('\n', stdout); // Print a final linefeed 

    close(sock); 
    exit(0); 
} 

그리고 테스트 이렇게 (2 터미널) :

[email protected]xServer:~./client_error_socket 192.168.1.7 "HELLO" 4444 
HelloReceived: HELLO 

[email protected]:~./server_error_socket 4444 
Handling client 192.168.1.7/56963 

(192.168.1.7) 대신 IP 주소를 사용하십시오.

희망 도움말.

감사합니다.

+0

안녕하세요, 오라클 버추얼 박스 우분투를 사용하고 있습니다. . ifconfig 후에 얻을 수있는 Ipaddress는 내가 옳다는 것을 희망한다. 나는 우분투 설정을 변경해야만한다. – Vivek

+0

@Vivek : IP 주소를 사용해야합니다 (기본적으로 VirtualBox는 192.168.xx 또는 10.xxx 또는 172.16.xx와 같은 개인 IP 주소를 제공합니다). 따라서 명령의 출력을 확인하십시오 ifconfig를 실행하고 주소를 지어 내면 ifconfig 예제를 찾을 수 있습니다 (http://www.thegeekstuff.com/2009/03/ifconfig-7-examples-to-configure-network-interface/) – TOC