c言語で通信を行うのを勉強し始めたのですが作成したプログラムがうまく動作しません。
下記は入力した小文字を大文字にして返すプログラムをTCP/IPで行うように作成しました。
linux上で行ってポート番号は9000、IPはループバックアドレスにしてます。
//サーバ側 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #define SOCK_NAME "./socket" int main() { int i; int fd1, fd2; struct sockaddr_in saddr; struct sockaddr_in caddr; int len; int ret; char buf[1024]; if ( ( fd1 = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 ) { perror( "socket" ); exit( 1 ); } memset( (char *)&saddr, 0, sizeof( saddr ) ); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr=INADDR_ANY; saddr.sin_port=htons(9000); strcpy( saddr.sin_port, SOCK_NAME ); unlink( SOCK_NAME ); if ( bind( fd1, ( struct sockaddr * )&saddr, ( socklen_t )sizeof( saddr ) ) < 0 ) { perror( "bind" ); exit( 1 ); } if ( listen( fd1, 5 ) < 0 ) { perror( "listen" ); exit( 1 ); } while( 1 ) { len = sizeof( caddr ); if ( ( fd2 = accept( fd1, ( struct sockaddr * )&caddr, ( socklen_t * ) &len ) ) < 0 ) { perror( "accept" ); exit( 1 ); } fprintf( stderr, "Connection established: socket %d used.\n", fd2 ); while( ( ret = read( fd2, buf, 1024 ) ) > 0 ) { fprintf( stderr, "read: %s\n", buf ); for ( i=0; i<ret; i++ ) if ( isalpha( buf[i] ) ) buf[i] = toupper( buf[i] ); fprintf( stderr, "write: %s\n", buf ); write( fd2, buf, strlen( buf )+1 ); fsync( fd2 ); } close( fd2 ); } close( fd1 ); return 0; }
//クライアント側 #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> #include <arpa/inet.h> #define SOCK_NAME "./socket" int main() { struct sockaddr_in saddr; struct in_addr sin_addr; int soc; char buf[1024]; if ( ( soc = socket( AF_INET, SOCK_STREAM, 0 ) ) < 0 ) { perror( "socket" ); exit( 1 ); } memset( (char *)&saddr, 0, sizeof( saddr ) ); saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = inet_addr("127.0.0.1"); saddr.sin_port=htons(9000); strcpy( saddr.sun_path, SOCK_NAME ); if ( connect( soc, ( struct sockaddr * )&saddr, ( socklen_t )sizeof( saddr ) ) < 0 ) { perror( "connect" ); exit( 1 ); } fprintf( stderr, "Connection established: socket %d used.\n", soc ); while( fgets( buf, 1024, stdin ) ) { if ( buf[strlen(buf)-1] == '\n' ) buf[strlen(buf)-1] = '\0'; write( soc, buf, strlen( buf )+1 ); fsync( soc ); read( soc, buf, 1024 ); fprintf( stdout, "%s\n", buf ); } close( soc ); return 0; }