ネットワークバイトオーダー
先日のEchoClient を実装したが動かず - Shammerismが動作しない原因は、ネットワークバイトオーダーに関係するものであったとわかった。具体的には、
// Build Destination Socket Informations memset(&destination_addr, 0, sizeof(destination_addr)); destination_addr.sin_family = AF_INET; destination_addr.sin_addr.s_addr = inet_addr(args[1]); destination_addr.sin_port = destination_port;
の部分を、
// Build Destination Socket Informations memset(&destination_addr, 0, sizeof(destination_addr)); destination_addr.sin_family = AF_INET; destination_addr.sin_addr.s_addr = inet_addr(args[1]); //destination_addr.sin_port = destination_port; destination_addr.sin_port = htons(destination_port);
とすることで動作するようになった。htons を忘れていたのが原因らしい。
そして、この htons が何をするか、ということについてだが、この関数自体は host to network short の略で、引数で渡されたデータ内容をネットワーク送信順に変換する、というもの。コンピューターの世界では、データはすべて0と1の羅列となる。0000とか、1111や、110011など、左右どちらから読んでも同じになるようなデータであれば何も問題は起きないが、
- 0011など、左右どちらか読むかで内容が異なってしまうようなデータである
- 送信側は左から読むことを意図してデータを送信
- 受信側は右から読むことを想定してデータを受信
という場合、送信側と受信側では異なったデータを扱うことになってしまう。こうした問題が起きないように、ネットワーク送信時にはビックエンディアン(データの最上位バイトを最下位アドレスに格納する方式)でやりとりする、というのが決まっているようだ。Intel CPU の場合は、この逆のリトルエンディアン形式でデータを扱うことになっているので、この変換を行っていないと通信がうまくいかなくなる、ということらしい。
(参考文献:http://www.amazon.co.jp/TCP-IPソケットプログラミング-C言語編-Michael-Donahoo/dp/4274065197)
ポートの値を htons することでうまくいったので、おそらく意図していないポートに接続しにいっていたのだろうと思う。一行しか変更していないが、変更後の全コードは以下。
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <arpa/inet.h> #include <netinet/in.h> int error_exit(char *message) { perror(message); exit(1); } int checknumber(char *v){ int len = strlen(v); int i; int result = 1; for(i = 0; i < len && result ; i++){ result = isdigit(v[i]); } return result; } int main(int argc, char *args[]){ if( argc != 3 && argc != 4 ) { printf("Usage: %s $ListenAddress $ListenPort $EchoMessage\n", args[0]); printf(" %s $ListenAddress $EchoMessage\n", args[0]); } else { if( checknumber(args[2]) != 1 ){ printf("%s is not number, the 2nd arguments has to be a number.\n", args[2]); } else { int sock; struct sockaddr_in destination_addr; unsigned short destination_port; char *echo_buffer[256]; unsigned int message_length; int receivedbytes, totalreceivedbyte; if( argc == 3 ){ destination_port = 7; } else if( argc == 4 ){ destination_port = atoi(args[2]); } // Socket open, this is a 1st step. if( (sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0 ){ error_exit("socket() failed.\n"); } // Build Destination Socket Informations memset(&destination_addr, 0, sizeof(destination_addr)); destination_addr.sin_family = AF_INET; destination_addr.sin_addr.s_addr = inet_addr(args[1]); destination_addr.sin_port = htons(destination_port); if( connect(sock, (struct sockaddr *)&destination_addr, sizeof(destination_addr)) < 0 ){ error_exit("connect() failed.\n"); } // Check echo message length message_length = strlen(args[3]); // Send message if( send(sock, args[3], message_length, 0) != message_length ){ error_exit("send() finished uncompletely...\n"); } } } return 0; }