recv 可以透過 flag 參數改變行為,例如 MSG_PEEK 能先「偷看」緩衝區資料而不把它清除——這正是它與 read 最大的差異,read 一旦把資料讀走,緩衝區就空了。readline 正是靠這個特性解決 TCP 黏包問題,例如 FTP 以 \r\n 作為一行結束的依據。
另外搭配 getsockname、getpeername 取得本端與對端位址,gethostname、gethostbyname、gethostbyaddr 則負責主機名稱與 IP 的互相轉換。
順手記兩個 vim 技巧:刪除當下行之後的所有行用 ,$d;刪除第一行到當前行用 1,.d。
/*
* socket03_echocli.cpp
*/
#include <arpa/inet.h>
#include <errno.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <netdb.h>
using namespace std;
#define ERR_EXIT(m) printf("error")
int getlocalip(char *ip)
{
char host[100] = {0};
if (gethostname(host, sizeof(host)) < 0)
return -1;
struct hostent *hp;
if ((hp = gethostbyname(host)) == NULL)
return -1;
strcpy(ip, inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]));
return 0;
}
int main(void)
{
char host[100] = {0};
if (gethostname(host, sizeof(host)) < 0)
ERR_EXIT("gethostname");
struct hostent *hp;
if ((hp = gethostbyname(host)) == NULL)
ERR_EXIT("gethostbyname");
int i = 0;
while (hp->h_addr_list[i] != NULL) {
printf("%s\n", inet_ntoa(*(struct in_addr*)hp->h_addr_list[i]));
i++;
}
char ip[16] = {0};
getlocalip(ip);
printf("localip=%s\n", ip);
return 0;
}
範例中原本拼寫為 innet_ntoa 的呼叫已修正為 inet_ntoa;另外 getlocalip 定義在 main 之前,因此不需額外宣告。若要處理 IPv6,可改用 getaddrinfo 搭配 inet_ntop,介面更一致。