關於socket編程相關知識點總結

來源:互聯網
上載者:User

  Socket介面是TCP/IP網路的API。流式Socket(SOCK_STREAM)是一種連線導向的Socket,針對於連線導向的TCP服務應用;資料報式Socket是一種不需連線的Socket,對應於不需連線的UDP服務應用。
  為了建立Socket,程式可以調用Socket函數,該函數返回一個類似於檔案描述符的控制代碼。

  關於socket編程的主要函數可以參考http://docs.huihoo.com/joyfire.net/9.html。

        下面是幾個位元組順序轉換函式:
·htonl():把32位值從主機位元組序轉換成網路位元組序
·htons():把16位值從主機位元組序轉換成網路位元組序
·ntohl():把32位值從網路位元組序轉換成主機位元組序
·ntohs():把16位值從網路位元組序轉換成主機位元組序

        首先,當accept函數監視的socket收到串連請求時,socket執行體將建立一個新的socket,執行體將這個新socket和請求串連進程的地址聯絡起來,收到服務要求的初始socket仍可以繼續在以前的 socket上監聽,同時可以在新的socket描述符上進行資料轉送操作。 
  Send()和recv()這兩個函數用於連線導向的socket上進行資料轉送。
  Send()函數原型為:
  int send(int sockfd, const void *msg, int len, int flags);
Sockfd是你想用來傳輸資料的socket描述符;msg是一個指向要發送資料的指標;Len是以位元組為單位的資料的長度;flags一般情況下置為0(關於該參數的用法可參照man手冊)。
  Send()函數返回實際上發送出的位元組數,可能會少於你希望發送的資料。在程式中應該將send()的傳回值與欲發送的位元組數進行比較。當send()傳回值與len不匹配時,應該對這種情況進行處理。
  recv()函數原型為:
  int recv(int sockfd,void *buf,int len,unsigned int flags);
  Sockfd是接受資料的socket描述符;buf 是存放接收資料的緩衝區;len是緩衝的長度。Flags也被置為0。Recv()返回實際上接收的位元組數,當出現錯誤時,返回-1共置相應的errno值。
Sendto()和recvfrom()用於在不需連線的資料報socket方式下進行資料轉送。由於本地socket並沒有與遠端機器建立串連,所以在發送資料時應指明目的地址。
sendto()函數原型為:
  int sendto(int sockfd, const void *msg,int len,unsigned int flags,const struct sockaddr *to, int tolen);
  該函數比send()函數多了兩個參數,to表示目地機的IP地址和連接埠號碼資訊,而tolen常常被賦值為sizeof (struct sockaddr)。Sendto 函數也返回實際發送的資料位元組長度或在出現發送錯誤時返回-1。
  Recvfrom()函數原型為:
  int recvfrom(int sockfd,void *buf,int len,unsigned int flags,struct sockaddr *from,int *fromlen);
  from是一個struct sockaddr類型的變數,該變數儲存源機的IP地址及連接埠號碼。fromlen常置為sizeof (struct sockaddr)。當recvfrom()返回時,fromlen包含實際存入from中的資料位元組數。Recvfrom()函數返回接收到的位元組數或當出現錯誤時返回-1,共置相應的errno。
如果你對資料報socket調用了connect()函數時,你也可以利用send()和recv()進行資料轉送,但該socket仍然是資料報socket,並且利用傳輸層的UDP服務。但在發送或接收資料報時,核心會自動為之加上目地和源地址資訊。

結束傳輸
  當所有的資料操作結束以後,你可以調用close()函數來釋放該socket,從而停止在該socket上的任何資料操作:
close(sockfd);
  你也可以調用shutdown()函數來關閉該socket。該函數允許你只停止在某個方向上的資料轉送,而一個方向上的資料轉送繼續進行。如你可以關閉某socket的寫操作而允許繼續在該socket上接受資料,直至讀入所有資料。
 附上一個用TCP協議進行檔案傳輸的基礎例子:

/*
 *This page contains a sever program that can send a flie to the client program.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/fcntl.h>

#define SERVER_PORT 12345
#define BUF_SIZE 4096 /* block transfer size */
#define QUEUE_SIZE 10 /* how many client can connect at the same time */

void fatal(char *string)
{
printf("%s/n",string);
exit(1);
}

int main(int argc,char * argv[])
{
 int s,b,l,fd,sa,bytes,on=1;
 char buf[BUF_SIZE]; /*buf for outgoing files*/
 struct sockaddr_in channel; /* hold IP address*/

    /* Build address structure to bind to socket. */  
    memset(&channel,0,sizeof(channel));
    channel.sin_family=AF_INET;
    channel.sin_addr.s_addr=htonl(INADDR_ANY);
    channel.sin_port=htons(SERVER_PORT);
   
    /* Passive open.Wait for connection. */
    s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);  /* Creat socket */
    if(s<0) fatal("socket failed");
    setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char *)&on,sizeof(on));

    b=bind(s,(struct sockaddr *)&channel,sizeof(channel));
    if(b<0) fatal("blind failed");

    l=listen(s,QUEUE_SIZE);
    if(l<0) fatal("listen failed");
    /* Socket is now set up and bound. Wait for connection and process it. */
    while(1){
     sa=accept(s,0,0);
     if(sa<0) fatal("accept failed");

     read(sa,buf,BUF_SIZE);

    /* Get and return the file. */
     fd=open(buf,O_RDONLY);
     if(fd<0) fatal("open failed");

     while(1){
   bytes=read(fd,buf,BUF_SIZE);
         if(bytes<=0) break;
   write(sa,buf,bytes);
  }

    close(fd);
    close(sa);
 }
    return 0;
}

 

/*
 *This page contains a client program that can request a flie from the server program.
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <strings.h>
#include <stdio.h>

#define SERVER_PORT 12345
#define BUF_SIZE 4096
void fatal(char *s);
int main(int argc,char * *argv)

{
    int c,s,bytes;
    char buf[BUF_SIZE];   /*buf for incoming files*/
    struct sockaddr_in channel;   /* hold IP address*/
   
    if (argc!=3)fatal("Usage:client IPaddress file-name");
 
    s=socket(PF_INET,SOCK_STREAM,IPPROTO_TCP);
    if(s<0)fatal("socket");
   
    bzero(&channel,sizeof(channel));
    channel.sin_family=AF_INET;
    channel.sin_port=htons(SERVER_PORT);
    if(inet_aton(argv[1],&channel.sin_addr)==0){      /* use the ASCII ip for the  server's sin_addr. */
 fprintf(stderr,"Inet_aton erro/n");
 exit(1);
     }
   
    c=connect(s,(struct sockaddr *)&channel,sizeof(channel));
    if(c<0)fatal("connetct failed");
   
    /* Connection is now established. Send file name including 0 byte at end. */
    write(s,argv[2],strlen(argv[2])+1);
   

    /* Go get the file and write it to standard output. */
    while(1){
       bytes=read(s,buf,BUF_SIZE);
       if(bytes<=0)exit(0);
       write(1,buf,bytes);
    }

return 0;
}

fatal(char *string)
{
printf("%s/n",string);
exit(1);
}

這個例子來自《電腦網路》第4版,略有修改,在UBUNTU下用gcc命令成功編譯,可以執行。

命令格式如下:

gcc -o XXX XXX.C

./XXX 127.0.0.1 FLIENAME

如果遇到這樣的問題:

 error: stray '/357' in program

應該是程式中含有中文字元,用LINUX下面的辦公軟體開啟,用二進位格式開啟就能很方便的看到是否有特殊的字元了,刪除改正往往能糾正問題。

 

 

ps:小弟初寫博文,新學的知識,可能有許多地方講解不對,請大家諒解,同時強烈希望也大家一起交流編程心得。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.