0
我在使用Telnet和echo在一行中讀取通過TCP套接字的客戶端輸入時出現問題。當使用一行telnet語句時,C socket讀取輸出空字符串
客戶端控制檯
devbox cehrig # telnet 127.0.0.1 50231
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Test Message
Connection closed by foreign host.
devbox cehrig # echo "One Liner" | telnet 127.0.0.1 50231
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Connection closed by foreign host.
devbox cehrig #
服務器控制檯
Mon Apr 6 16:36:41 2015: Accepting connections...
Mon Apr 6 16:36:45 2015: Inbound connection from 127.0.0.1
Client msg: Test Message
Mon Apr 6 16:36:48 2015: Accepting connections...
Mon Apr 6 16:44:06 2015: Inbound connection from 127.0.0.1
Client msg:
Mon Apr 6 16:44:06 2015: Accepting connections...
「客戶消息」 保持空時:只當我輸入的消息在 '正常' 的telnet會話工作試圖用echo「」|發送數據遠程登錄....
這是我使用的是從客戶端套接字讀取功能:
void read_socket(int idntef,
config_t * cfg)
{
int n;
char * _buf = (char *) malloc(512*sizeof(char));
char * _cor = (char *) malloc(512*sizeof(char));
char * _out = _cor;
bzero(_buf, 512);
bzero(_cor, 512);
if((n = read(idntef, _buf, 511)) < 0) {
_print(stderr, "messages.socketreadfail", cfg, 1);
_exit(0);
}
int x = 0;
while(*_buf != '\n' && x++ <= 512) {
*_cor++ = *_buf++;
}
printf("Client msg: %s\n", _out);
fflush(stdout);
shutdown(idntef, 2);
}
SBD是否有我一個提示,是什麼在這裏改進?
'而(!* _ BUF = '\ n' && X ++ <= 512){'是錯誤的。你應該對'n'變量進行測試。 Plus:不需要只讀511個字節到512大小的緩衝區('if((n = read(idntef,_buf,511))<0){') – wildplasser
在我的Mac上(運行OS X 10.10.2)至少,回聲| telnet技巧不起作用;它會導致telnet連接,然後立即斷開而不發送任何字符。 –
telnet是一個協議,它需要連接到一個telnet進程。 (有一堆握手要執行)獨立的'read()'將不能正確設置telnet連接。 – user3629249