2012-12-26 63 views
0

我用Python來編寫代碼。現在我正在嘗試C++。當我運行該程序時,即使使用htonl,我也會看到目標地址(w/Wireshark)反向。在Python中,這個程序工作正常。 按照代碼。在底部我打印結果。 我使用的是Ubuntu 12.04LTS和g ++(Ubuntu/Linaro 4.6.3)。反向目標地址

//UdpClient.cpp 
#include <iostream> 
#include <string> 
#include <sstream> 
#include <sys/socket.h> 
#include <sys/types.h> 
#include <netdb.h> 
#include <cstdlib> 
#include <arpa/inet.h> 
#include <typeinfo> 
using namespace std; 

int main(int argc, char* argv[]) 
{ 
    int s, p, rb,rs; 
    int bytesend; 
    char buf[1024]; 
    int len; 
    char ent[16]; 
    char Porta[5]; 
    unsigned long EndServ; 
    struct sockaddr_in UdpServer, UdpClient; 
    int UdpServerLen = sizeof(UdpServer); 
    //do text 
    string msg("The quick brown fox jumps over the lazy dog\n"); 
    len = msg.copy(buf, msg.size(), 0); 

    buf[len] = '\0'; 
    //do socket 
    s = socket(AF_INET, SOCK_DGRAM, 0); 
    if (s == -1){ 
     cout << "No socket done\n"; 
    } 
    else { 
     cout << "Socket done\n"; 
    } 
    //populate UdpClient struct 
    UdpClient.sin_family = AF_INET; 
    UdpClient.sin_addr.s_addr = INADDR_ANY; 
    UdpClient.sin_port = 0; 
    //populate UdpServer struct 
    UdpServer.sin_family = AF_INET; 
    UdpServer.sin_addr.s_addr = inet_addr(argv[1]); 
    //check if addres is correct 
    cout << "ServerAddress: " << hex << UdpServer.sin_addr.s_addr << endl; 
    UdpServer.sin_port = htons(atoi(argv[2])); 
    //bind socket 
    rb = bind(s, (struct sockaddr *)&UdpClient, sizeof(UdpClient)); 
    if (rb == 0){ 
     cout << "Bind OK!\n"; 
    } 
    else { 
     cout << "Bind NOK!!!\n"; 
     close(s); 
     exit(1); 
    } 
    //send text to Server 
    cout << "UdpServSiz: " << sizeof(UdpServer) << endl; 
    rs = sendto(s, buf, 1024, 0, (struct sockaddr *)&UdpServer, sizeof(UdpServer)); 
    if (rs == -1){ 
     cout << "Message NOT sent!!!\n"; 
    } 
    else { 
     cout << "Message SENT!!!\n"; 
    } 
    close(s); 
    return 0; 
} 
/* 
    [email protected]:~/CmmPGMs$ ./UdpClient 127.0.0.1 6789 
    Socket done 
    ServerAddress: 100007f (using htonl or not!!) 
    Bind OK! 
    Message SENT!!! 
    [email protected]:~/CmmPGMs$ 
*/ 
+0

照顧你的[排列順序](http://en.wikipedia.org/wiki/Endianness)! – m0skit0

+0

htonl和inet_addr應該照顧到這一點。 – Lukior

回答

1

聽起來像你在ARM(Linaro)?在這種情況下,處理器的字節順序與網絡順序相匹配,所以htonl和ntohl基本上什麼都不做。