當前位置:首頁 » 操作系統 » linuxtcp代碼

linuxtcp代碼

發布時間: 2024-12-18 18:48:50

A. linux C 進行TCP網路連接,怎樣設置連接超時時間

如果你確定,真的不需要等這么久,或者用戶希望可以隨時中上連接過程,那麼一般是用 非阻塞模式來做的. 看看我的這段連接代碼(節選),可以作為TCP連接的典範:

bool CRemoteLink::Connect()
{
OnDisconnected(); // 如果已經連接,則斷開

if(!m_bUseProxy)
{

m_iConnStatus = SS_CONNECTING; // 正在連接狀態
GNTRACE ("開始連接到遠程伺服器[%s][%ld]...\n", m_strip.c_str(), m_port);

// 建立套接字, 准備連接到伺服器
m_socket = ::socket(AF_INET, SOCK_STREAM, 0);
if (socket < 0) {
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_CREATE, MSG_SE_CREATE);
return false;
}

// 設為非同步操作方式
unsigned long on = 1;
if (::ioctlsocket(m_socket, FIONBIO, &on) < 0) {
::closesocket(m_socket);
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_CREATE, MSG_SE_CREATE);
return false;
}

sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(m_strip.c_str());
addr.sin_port = htons(m_port);

int rt;
rt = ::connect(m_socket, (sockaddr *) &addr, sizeof(addr));
if (rt == 0) {
OnConnected();
return true;
}

// ==================================================================
timeval to;

// 首先建立連接
fd_set wfds;
fd_set efds;
FD_ZERO(&wfds);
FD_ZERO(&efds);

// test shutdown event each 100ms.
to.tv_sec = 0;
// CONNECT_TIMEOUT;
to.tv_usec = 100000;

int it = 0;
while(!m_meShutdown.Wait(0) && !m_meConnStop.Wait(0))
{
FD_SET(m_socket, &wfds);
FD_SET(m_socket, &efds);
int n = select(m_socket + 1, NULL, &wfds, &efds, &to);

if (n > 0) {
if(FD_ISSET(m_socket, &wfds))
{
OnConnected();
return true;
}
else
{
//int err = ::WSAGetLastError();
//const char* msg = GetLastErrorMessage(err);
GNTRACE ("CRemoteLink::Connect : connection attempt failed!\n");
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_CONN, MSG_SE_CONN);
break;
}
} else if (n < 0) { // Select Error
int err = ::WSAGetLastError();
const char* msg = GetLastErrorMessage(err);
GNTRACE ("CRemoteLink::Connect : Select Error.[%d] - %s\n", err, msg);
if(m_pCallBack)
m_pCallBack->OnSocketError(err, msg);
break;
}
else
{
it += 100;
if(it > 30000) // 連接超時 -- (30S)
{
GNTRACE ("CRemoteLink::Connect : Time out.\n");
if(m_pCallBack)
m_pCallBack->OnSocketError(SE_TIMEOUT, MSG_SE_TIMEOUT);
break;
}
}
}
if(m_meConnStop.Wait(0))
{
GNTRACE("連接過程進行時被取消。\n");
}
}
else
{
// 通過代理伺服器連接

B. linux shell 鑴氭湰瀹炵幇tcp/upd鍗忚閫氳

linux 璁懼囬噷闈㈡湁涓姣旇緝鐗規畩鐨勬枃浠:

/dev/[tcp|upd]/host/port 鍙瑕佽誨彇鎴栬呭啓鍏ヨ繖涓鏂囦歡錛岀浉褰撲簬緋葷粺浼氬皾璇曡繛鎺:host 榪欏彴鏈哄櫒錛屽瑰簲port絝鍙c傚傛灉涓繪満浠ュ強絝鍙e瓨鍦錛屽氨寤虹珛涓涓猻ocket 榪炴帴銆傚皢鍦錛/proc/self/fd鐩褰曚笅闈錛屾湁瀵瑰簲鐨勬枃浠跺嚭鐜般

涓銆佹祴璇曚笅錛/dev/tcp/host/post鏂囦歡

澶嶅埗浠g爜

   

浠g爜濡備笅:

[chengmo@centos5 shell]$ cat/dev/tcp/127.0.0.1/22

   SSH-2.0-OpenSSH_5.1

   #鎴戠殑鏈哄櫒shell絝鍙f槸錛22

   #瀹為檯:/dev/tcp鏍規湰娌℃湁榪欎釜鐩褰曪紝榪欐槸灞炰簬鐗規畩璁懼

   [chengmo@centos5 shell]$ cat/dev/tcp/127.0.0.1/223

   -bash: connect: 鎷掔粷榪炴帴

   -bash: /dev/tcp/127.0.0.1/223: 鎷掔粷榪炴帴

   #223鎺ュ彛涓嶅瓨鍦,鎵撳紑澶辮觸

   [chengmo@centos5 shell]$ exec 8/dev/tcp/127.0.0.1/22

   [chengmo@centos5 shell]$ ls -l /proc/self/fd/

   鎬昏 0

   lrwx------ 1 chengmo chengmo 64 10-21 23:05 0 - /dev/pts/0

   lrwx------ 1 chengmo chengmo 64 10-21 23:05 1 - /dev/pts/0

   lrwx------ 1 chengmo chengmo 64 10-21 23:05 2 - /dev/pts/0

   lr-x------ 1 chengmo chengmo 64 10-21 23:05 3 - /proc/22185/fd

   lrwx------ 1 chengmo chengmo 64 10-21 23:05 8 - socket:[15067661]

   #鏂囦歡鎻忚堪絎8錛屽凡緇忔墦寮涓涓猻ocket閫氳閫氶亾錛岃繖涓鏄涓涓鍙浠ヨ誨啓socket閫氶亾,鍥犱負鐢錛""鎵撳紑

   [chengmo@centos5 shell]$ exec 8-

   #鍏抽棴閫氶亾

   [chengmo@centos5 shell]$ ls -l /proc/self/fd/

   鎬昏 0

   lrwx------ 1 chengmo chengmo 64 10-21 23:08 0 - /dev/pts/0

   lrwx------ 1 chengmo chengmo 64 10-21 23:08 1 - /dev/pts/0

   lrwx------ 1 chengmo chengmo 64 10-21 23:08 2 - /dev/pts/0

   lr-x------ 1 chengmo chengmo 64 10-21 23:08 3 - /proc/22234/fd

浜屻侀氳繃閲嶅畾鍚戣誨彇榪滅▼web鏈嶅姟鍣ㄥご淇℃伅

澶嶅埗浠g爜

   

浠g爜濡備笅:

#!/bin/sh

   #testhttphead.sh

   #瀹炵幇閫氳繃涓繪満鍚嶏紝絝鍙h誨彇web 鏈嶅姟鍣╤eader淇℃伅

   #right chengmo,qq:8292669

   if(($#2));then

   echo "usage:$0 host port";

   exit 1;

   fi

   #濡傛灉鍙傛暟緙哄け錛岄鍑虹▼搴忥紝榪斿洖鐘舵1

   exec 6/dev/tcp/$1/$2 2/dev/null;

   #鎵撳紑host鐨刾ort 鍙璇誨啓鐨剆ocket榪炴帴錛屼笌鏂囦歡鎻忚堪絎6榪炴帴

   if(($?!=0));then

   echo "open $1 $2 error!";

   exit 1;

   fi

   #濡傛灉鎵撳紑澶辮觸錛$?榪斿洖涓嶄負0錛岀粓姝㈢▼搴

   echo -e "HEAD / HTTP/1.1/n/n/n/n/n"6;

   #灝咹EAD 淇℃伅錛屽彂閫佺粰socket榪炴帴

   cat6;

   #浠巗ocket璇誨彇榪斿洖淇℃伅錛屾樉紺轟負鏍囧噯杈撳嚭

   exec 6-;

   exec 6-;

   #鍏抽棴socket鐨勮緭鍏ワ紝杈撳嚭

   exit 0;

鑴氭湰寤虹珛鍚庯細瀛樹負testhttphead.sh

榪愯岀粨鏋滐細

澶嶅埗浠g爜

   

浠g爜濡備笅:

[chengmo@centos5 ~/shell]$ sh testhttphead.sh www..com 80

   HTTP/1.1 200 OK

   Date: Thu, 21 Oct 2010 15:17:23 GMT

   Server: BWS/1.0

   Content-Length: 6218

   Content-Type: text/html;charset=gb2312

   Cache-Control: private

   Expires: Thu, 21 Oct 2010 15:17:23 GMT

   Set-Cookie: BAIDUID=:FG=1; expires=Thu, 21-Oct-40 15:17:23 GMT; path=/; domain=..com

   P3P: CP=" OTI DSP COR IVA OUR IND COM "

   Connection: Keep-Alive

   [chengmo@centos5 ~/shell]$ sh testhttphead.sh 127.0.0.1 8080

   open 127.0.0.1 8080 error!

紿佺劧鏈変釜濂囨鎯蟲硶錛

鎴戜滑鍦╳indows鏃朵唬灝遍氳繃telnet 鍙浠ュ疄鐜皌cp/upd鍗忚閫氳錛岄偅涔堝傛灉鐢ㄤ紶緇熸柟娉曟庝箞瀹炵幇鍛錛

澶嶅埗浠g爜

   

浠g爜濡備笅:

[chengmo@centos5 ~/shell]$ echo -e "HEAD / HTTP/1.1/n/n/n/n/n"|telnet www..com 80

   Trying 220.181.6.175...

   Connected to www..com.

   Escape character is '^]'.

   Connection closed by foreign host.

   #鐩存帴緇欏彂閫侊紝澶辮觸

   [chengmo@centos5 ~/shell]$ (telnet www..com 80)EOF

   HEAD / HTTP/1.1

   EOF

   Trying 220.181.6.175...

   Connected to www..com.

   Escape character is '^]'.

   Connection closed by foreign host.

   #閲嶅畾鍚戣緭鍏ワ紝榪樻槸澶辮觸錛

鎵懼埌姝g『鏂規硶錛

澶嶅埗浠g爜

   

浠g爜濡備笅:

[chengmo@centos5 shell]$ (echo -e "HEAD / HTTP/1.1/n/n/n/n/n";sleep 2)|telnet www..com 80

   Trying 220.181.6.175...

   Connected to www..com.

   Escape character is '^]'.

   HTTP/1.1 200 OK

   Date: Thu, 21 Oct 2010 15:51:58 GMT

   Server: BWS/1.0

   Content-Length: 6218

   Content-Type: text/html;charset=gb2312

   Cache-Control: private

   Expires: Thu, 21 Oct 2010 15:51:58 GMT

   Set-Cookie: BAIDUID=:FG=1; expires=Thu, 21-Oct-40 15:51:58 GMT; path=/; domain=..com

   P3P: CP=" OTI DSP COR IVA OUR IND COM "

   Connection: Keep-Alive

   #鎴愬姛浜嗭紒鍔犲叆sleep 灞呯劧鍙浠ヤ簡錛宻leep 鏀規垚1縐掍篃鍙浠

鏄涓嶆槸鐢變簬sleep鍚庯紝echo浼氭帹鍑2縐掑彂緇欓氶亾錛歵elnet鍛錛熸帹璁哄彲浠ヤ粠榪2涓鏂歸潰鎺ㄧ炕錛

涓涓鏂歸潰錛氶氳繃()鎷鐨勬暟鎹鏄涓瀵瑰懡浠わ紝浼氫綔涓轟竴涓瀛愬懡浠ゆ墽琛岋紝涓璧鋒墽琛屽畬紼嬪簭緇撴潫銆傛瘡涓鍛戒護echo璇鍙ワ紝灝辯洿鎺ュ彂閫佸埌灞忓箷錛堜篃灝辨槸鏍囧噯杈撳嚭錛夛紝鍙瑕佹湁鏍囧噯杈撳嚭浜嗭紝灝變細閫氳繃閫氶亾椹涓婁紶涓錛歵elnet 錛屽傛灉鎺ヤ笅鏉ュ懡浠よ繕鏈夎緭鍑猴紝浼氭敞鎰忎紶緇檛elnet 錛岀洿鍒()鍐呮墍鏈夊懡浠ゆ墽琛屽畬錛屼笌閫氶亾榪炴帴灝辨柇寮浜嗐

鍐嶄竴涓鏂歸潰錛氬傛灉璇存槸璧峰埌鎺ㄨ繜鍙戦佺殑璇濓紝浠涔堟椂鍊欐湁鏁版嵁榪囨潵錛屽彂緇檛elnet錛屼粈涔堟椂鍊檛elnet鍛戒護鍚鍔ㄣ傝窡浣犳帹榪熶竴鐐硅繕鏄鏃╀竴鐐瑰彂閫佽繃鏉ャ傛病鏈夊叧緋匯

榪欑嶇被鍨嬪懡浠わ紝鐪嬪嚭sleep錛屽叾瀹炲氨鏄淇濇寔閫氶亾璺焧elnet 榪炴帴2縐掗挓銆 閫氶亾榪炴帴鐫浜嗭紝telnet緇堢杈撳叆涔熻繕鍦錛屽洜姝ゅ彲浠ヤ繚鎸佷粠鏈嶅姟鍣ㄨ幏寰楁暟鎹銆

鎵浠,寤惰繜澶氫箙錛岃繕鏄璺熸湇鍔″櫒澶勭悊閫熷害鏈夊叧緋匯

濡傛灉閫氳繃echo 鍚憈elnet鍙戦佹暟鎹錛屼繚鎸侀氶亾鑱旈氾紝浣跨敤sleep鏄涓寰堝ソ鏂規硶銆

閫氳繃閲嶅畾鍚戠粰telnet杈撳叆鍙傛暟榪欑嶆柟娉曪紝鎴戣繕鎯充笉鍒版庝箞鏍峰疄鐜板歡榪熻緭鍏ャ傛湁鐭ラ亾鏈嬪弸錛屽彲浠ユ寚鐐規寚鐐.

鍖哄埆錛

telnet涓巈cho 瀹炵幇 http璁塊棶錛屼笌閫氳繃鎵撳紑璇誨啓socket鏄涓嶄竴鏍風殑錛屾墦寮socket閫氶亾錛屾槸鍙浠ヨ繘琛屼氦鎹㈠勭悊鐨勩備紶鍏ュ懡浠わ紝媧誨姩緇撴灉錛屽啀浼犲叆鍛戒護錛屽啀鑾峰緱緇撴灉銆倀elnet閫氳繃echo 灝變笉鑳借繖鏍峰勭悊浜嗐

涓夈侀氳繃shell鑴氭湰閲嶅畾鍚戝疄鐜扮洃鎺memcache鐘舵

澶嶅埗浠g爜

   

浠g爜濡備笅:

#!/bin/sh

   #閫氳繃浼犲叆ip 浠ュ強絝鍙o紝鍙戦佹寚浠よ幏寰楄繑鍥炴暟鎹

   #right chengmo qq:8292669

   #鍑芥暟寰寰鏀懼埌鏈涓婇潰

   function sendmsg()

   {

   msg=$1;

   echo "$1"8;

   getout;

   }

   #鍚憇ocket閫氶亾鍙戦佹寚浠わ紝騫朵笖璋冪敤鑾峰緱榪斿洖鍙傛暟

   function getout()

   {

   #read 鍛戒護 -u 浠庢墦寮鏂囦歡鎻忚堪絎 8 璇誨彇鏁版嵁錛-d璇誨彇鏁版嵁蹇界暐鎺:/r鎹㈣岀

   while read -u 8 -d $'/r' name;

   do

   if [ "${name}" == "END" -o "${name}" == "ERROR" ];then

   break;

   fi;

   echo $name;

   done

   }

   #鐢變簬錛歮emcached姣忔¢氳瀹屾瘯錛屼細榪斿洖錛欵ND鎴栬匛RROR(鍑洪敊錛夛紝閫氳繃鍒ゆ柇鏄鍚︽槸"END"瑙夊緱璇誨彇鏄涓嶆槸緇撴潫錛屽惁鍒欏驚鐜涓嶄細鍋滄

   if [ $# -lt 2 ];then

   echo "usage:$0 host port [command]";

   exit 1;

   fi;

   [[ $# -gt 2 ]]command=$3;

   #璁劇疆榛樿ゅ 濡傛灉command涓哄畾涔夊垯涓猴細stats

   command="${command=stats}";

   host="$1";

   port="$2";

   exec 8/dev/tcp/${host}/${port};

   #鎵撳紑閫氬悜閫氶亾鏄8

   if [ "$?" != "0" ];then

   echo "open $host $port fail!";

   exit 1;

   fi

   sendmsg "$command";

   #鍙戦佹寚瀹氬懡浠

   sendmsg "quit";

   #鍙戦侀鍑洪氬悜鍛戒護

   exec 8-;

   exec 8-;

   #鍏抽棴socket閫氶亾

   exit 0;

榪欐槸閫氳繃閲嶅畾鍚戱紝瀹炵幇socket閫氳涓錛屽彂閫佺劧鍚庤幏鍙栬繑鍥炵殑渚嬪瓙銆傚叾瀹烇紝涓婇潰浠g爜鐪嬩技涓嬈″彧鑳藉彂閫佷竴孌點傛椂闂翠笂銆傛垜浠鍙浠ュ弽澶嶈皟鐢錛歴endmsg 錛屾崟鎹夎緭鍑烘暟鎹銆傚疄鐜拌繛緇鐨勶紝璇諱笌鍐欐搷浣溿

瀹炰緥鎴鍥撅細

鍏跺畠瀹炵幇鏂規硶錛

鍏跺疄閫氳繃錛歵elnet涔熷彲浠ュ疄鐜扮殑銆

[chengmo@centos5 shell]$ (echo "stats";sleep 2)|telnet 127.0.0.1 11211

閫氳繃nc鍛戒護瀹炵幇錛

[chengmo@centos5 shell]$ (echo "stats")|nc 127.0.0.1 11211

涓嶉渶瑕佸姞寤惰繜錛岀洿鎺ユ墦寮閫氶亾

絎浜屼釜紼嬪簭閲岄潰錛岀湅鍒皊hell瀹屽叏鍙浠ュ勭悊浜や簰璁捐′簡銆傚傛灉鎸夌収榪欐牱錛岀櫥闄唂tp,pop3,stmp閮藉彲浠ョ被浼煎疄鐜般傝繖浜涳紝鎴戜滑閫氳繃shell socket綾諱技紼嬪簭瀹炵幇錛屽簲璇ヤ笉鍥伴毦錛屽彧鏄鎹曟崏濡傚彂閫佽В鏋愮殑闂棰樹簡銆

C. LinuxC編程建立TCP連接linuxctcp

Linux C編程:建立 TCP連接
Linux C編程中使用TCP(Transmission Control Protocol,傳輸控制協議)協議建立客戶端和伺服器之間連接的過程稱之為TCP連接,是一種可靠而強大的通信協議,在Linux C編程中可用於建立資料庫、網路通信等等。本文介紹了在Linux C編程中如何建立TCP連接,以及其中遇到的一些問題。
在Linux C語言編程中,可以使用socket()函數建立一個TCP連接。socket()函數的第一個參數指定協議族,例如AF_INET指定IPV4協議族,第二個參數指定套接字類型,例如SOCK_STREAM指定流式套接字。
接下來,可以使用bind()函數將套接字與系統分配的IP地址和埠綁定,然後使用listen()函數使套接字變為被動模式,並啟動監聽進程,此時伺服器已准備就緒,等待客戶端的連接。最後,使用accept()函數接受客戶端的連接,當接受到客戶端的連接後,伺服器就可以使用建立的socket與客戶端通信了。
示例代碼如下:
// 創建 socket
int sockfd;
struct sockaddr_in addr;
// AF_INET: IPV4 協議族
// SOCK_STREAM: 流式套接字
sockfd = socket(AF_INET, SOCK_STREAM, 0);
// 設置 IP 地址
addr.sin_family = AF_INET;
addr.sin_port = htons(9999); //埠號
addr.sin_addr.s_addr = inet_addr(“127.0.0.1”); //IP地址
// 綁定 IP 和 埠
bind(sockfd, (struct sockaddr*)&addr, sizeof(addr));
// 監聽客戶端請求
listen(sockfd, 20);
// 接受 客戶端連接請求
struct sockaddr_in client_addr;
socklen_t client_addr_len;
int client_fd = accept(sockfd, (struct sockaddr*)&client_addr,
&client_addr_len);
上述步驟完成後,客戶端和伺服器的TCP連接建立完畢。在Linux C編程中,使用TCP協議建立客戶端和伺服器之間連接過程雖然繁瑣,但是它可以實現可靠的數據傳輸和優秀的網路通信,這個代價值得支付。
總而言之,在Linux C編程中使用TCP協議建立客戶端和伺服器之間連接,可以通過socket()、bind()、listen()、accept()等函數將客戶端和伺服器建立可靠的數據傳輸連接,這是一個蠻耗時的過程,但也值得支付,因為通過這種方式可以實現穩定的網路通信。

熱點內容
sql注入就是xss 發布:2024-12-18 22:03:15 瀏覽:162
蘋果跑分和安卓跑分有什麼區別 發布:2024-12-18 21:47:41 瀏覽:505
c語言好考嗎 發布:2024-12-18 21:43:20 瀏覽:291
陌陌密碼忘了手機號也換了怎麼辦 發布:2024-12-18 21:21:03 瀏覽:191
軒逸建議買什麼配置 發布:2024-12-18 21:19:29 瀏覽:193
手工反編譯 發布:2024-12-18 21:14:39 瀏覽:902
後台ui源碼 發布:2024-12-18 21:01:14 瀏覽:216
腳本刷曹仁 發布:2024-12-18 21:00:15 瀏覽:759
c語言是怎麼實現跨平台編譯的 發布:2024-12-18 20:55:20 瀏覽:997
電腦伺服器機箱定做 發布:2024-12-18 20:51:03 瀏覽:903