转:http://www.linuxforu.com/2011/12/socket-api-part-5-sctp/

By Pankaj Tanwar on December 29, 2011 in CodingDevelopers · 11 Comments

This article on socket programming deals with the Stream Control Transmission Protocol (SCTP).

Similar to TCP and UDP, SCTP provides some features of both. It is message-oriented, and provides a reliable sequenced delivery of messages. SCTP supports multi-homing, i.e., multiple IPs on both sides of the connection. So it is called an association instead of a connection, as a connection involves communication between two IPs, while an association refers to communication between two systems that may have multiple IPs.

SCTP can provide multiple streams between connection endpoints, and each stream will have its own reliable sequenced delivery of messages, so any lost message will not block the delivery of messages in any of the other streams. SCTP is not vulnerable to SYN flooding, as it requires a 4-way handshake.
We will discuss the science later, and now jump to the code, as we usually do. But first you need to know the types of SCTP sockets:

  • A one-to-one socket that corresponds to exactly one SCTP association (similar to TCP).
  • A one-to-many socket, where many SCTP associations can be active on a socket simultaneously (similar to UDP receiving datagrams from several endpoints).

One-to-one sockets (also called TCP-style sockets) were developed to ease porting existing TCP applications to SCTP, so the difference between a server implemented using TCP and SCTP is not much. We just need to modify the call to socket() to socket(AF_INET, SOCK_STREAM, and IPPROTO_SCTP) while everything else stays the same — the calls to listen()accept() for the server, and connect() for the client, with read() and write() calls for both.

Now let’s jump to the one-to-many or UDP-style socket, and write a server using multiple streams that the client follows.

First, here is the code for the server, smtpserver.c:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
#include <arpa/inet.h>
 
 
#define MAX_BUFFER  1024
 
int main()
{
    int sfd, cfd, len, i;
    struct sockaddr_in saddr, caddr;
    struct sctp_initmsg initmsg;
    char buff[INET_ADDRSTRLEN];
    char buffer[MAX_BUFFER+1] = "Message ##\n";
 
 
    sfd = socket( AF_INET, SOCK_STREAM, IPPROTO_SCTP );
 
    bzero( (void *)&saddr, sizeof(saddr) );
    saddr.sin_family = AF_INET;
    saddr.sin_addr.s_addr = htonl( INADDR_ANY );
    saddr.sin_port = htons(29008);
 
    bind( sfd, (struct sockaddr *)&saddr, sizeof(saddr) );
 
/* Maximum of 3 streams will be available per socket */
    memset( &initmsg, 0, sizeof(initmsg) );
    initmsg.sinit_num_ostreams = 3;
    initmsg.sinit_max_instreams = 3;
    initmsg.sinit_max_attempts = 2;
    setsockopt( sfd, IPPROTO_SCTP, SCTP_INITMSG,
            &initmsg, sizeof(initmsg) );
 
    listen( sfd, 5 );
 
    for(;;) {
        printf("Server Running\n");
 
        len=sizeof(caddr);
        cfd=accept(sfd, (struct sockaddr *)&caddr, &len);
         
        printf("Connected to %s\n",
            inet_ntop(AF_INET, &caddr.sin_addr, buff,
            sizeof(buff)));
 
         
        for(i=0; i< 3; i++) {
/* Changing 9th character the character after # in the message buffer */
            buffer[9] = '1'+i;
 
            sctp_sendmsg( cfd, (void *)buffer, (size_t)strlen(buffer),
                    NULL, 0, 0, 0, i /* stream */, 0, 0 );
            printf("Sent: %s\n", buffer);
        }
 
        close( cfd );
    }
    return 0;
}

And here’s the code of the client, sctpclient.c:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/sctp.h>
 
#define MAX_BUFFER  1024
 
int main(int argc, char **argv)
{
    int cfd, i, flags;
    struct sockaddr_in saddr;
    struct sctp_sndrcvinfo sndrcvinfo;
    struct sctp_event_subscribe events;
    struct sctp_initmsg initmsg;
    char buffer[MAX_BUFFER+1];
 
    if(argc!=2) {
        printf("Usage: %s ipaddress\n", argv[0]);
    return -1;
    }
 
    cfd = socket( AF_INET, SOCK_STREAM, IPPROTO_SCTP );
 
/* Specify that a maximum of 3 streams will be available per socket */
    memset( &initmsg, 0, sizeof(initmsg) );
    initmsg.sinit_num_ostreams = 3;
    initmsg.sinit_max_instreams = 3;
    initmsg.sinit_max_attempts = 2;
    setsockopt( cfd, IPPROTO_SCTP, SCTP_INITMSG,
            &initmsg, sizeof(initmsg) );
 
    bzero( (void *)&saddr, sizeof(saddr) );
    saddr.sin_family = AF_INET;
    inet_pton(AF_INET, argv[1], &saddr.sin_addr);
    saddr.sin_port = htons(29008);
     
    connect( cfd, (struct sockaddr *)&saddr, sizeof(saddr) );
 
    memset( (void *)&events, 0, sizeof(events) );
    events.sctp_data_io_event = 1;
    setsockopt( cfd, SOL_SCTP, SCTP_EVENTS,
        (const void *)&events, sizeof(events) );
 
     
/* Sending three messages on different streams */
 
    for (i=0; i<3; i++) {
        bzero( (void *)&buffer, sizeof(buffer) );
 
        sctp_recvmsg( cfd, (void *)buffer, sizeof(buffer),
                        (struct sockaddr *)NULL, 0, &sndrcvinfo, &flags );
 
        printf("Received following data on stream %d\n\n%s\n",
            sndrcvinfo.sinfo_stream, buffer);
 
    }
 
    close(cfd);
 
    return 0;
}

The server is sending three messages on three different streams, and the client is just receiving the messages and printing them on the screen (see Figures 1 and 2).

Figure 1: Server output

Figure 2: Client output

The code is similar to the TCP client, as we are again making calls to the same functions [refer toParts 123 and 4 of this series.]. The difference is that we are creating an iterative server, similar to the one for UDP, but we have an accept() call here. The client does the reverse, and receives the messages coming from the server to the client. Now let’s try to understand the functions that we used:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/sctp.h>
 
int sctp_sendmsg (int sd, const void *msg, size_t len,
    struct sockaddr *to, socklen_t tolen, uint32_t ppid, uint32_t
    flags, uint16_t stream_no, uint32_t timetolive, uint32_t context);

We are using this function to send a message from a socket while using the advanced features of SCTP. The first argument to the function is sd, the socket descriptor, from which the messagemsg of length len is sent. The fourth argument is to give the destination address — tolenspecifies the length of the destination address, while stream_no identifies the stream number to send this message to. The flags parameter is used to send some options to the receiver. You can check out the manual pages for sctp_sendmsg().

The timetolive parameter is time in milliseconds after which the message will expire if not sent by then; the zero here indicates that no time-out is set. The context is the value passed to the upper layer along with the undelivered message, if an error occurs while sending the message. When successful, it will return the number of bytes sent, or -1 on error.

Next is the stcp_recvmsg() function:

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/sctp.h>
 
int sctp_recvmsg(int sd, void * msg, size_t len, struct
    sockaddr * from, socklen_t * fromlen, struct sctp_sndrcvinfo
    * sinfo, int * msg_flags);

This function does the reverse of the sctp_sendmsg function and is used to receive a message. The parameters are similar. The socket sd receives the msg of length len from the address *fromwith a length *fromlen, and *sinfo is a pointer to the address, which will be filled upon receipt of the message. mag_flags is a pointer to an integer with flags like MSG_NOTIFICATION or MSG_EOR. It returns the number of bytes received, or -1 on error.

#include <sys/types.h>
#include <sys/socket.h>
 
int setsockopt(int sockfd, int level, int optname,
                      const void *optval, socklen_t optlen);

This function is used to set the options for the socket sockfd. The next argument is the level at which the option resides. To manipulate options at the sockets API level, the level is specified asSOL_SOCKEToptname and any specified options are passed uninterpreted to the appropriate protocol module for interpretation. The level and optname are defined in sys/sockets.h. The arguments optval and optlen are used to access option values for setsockopt() that are stored in the structure. The options we set in the server are:

initmsg.sinit_num_ostreams = 3;
initmsg.sinit_max_instreams = 3;
initmsg.sinit_max_attempts = 2;

Here, the first two lines tell us that the output and input streams available are three, and the maximum attempts will be two. The same options are set in the client program. Other options are set for the events. This structure will be filled when an event like “message received” occurs, and our program is notified. Its counterpart function is getsockopts() (look up the man pages for help). The rest of the code is simple to understand.

Now compile and run the program; make sure you have installed sctp-tools so that you’ll havesctp.h at netinet/. To compile, use gcc sctpserver.c -lsctp -o server && gcc sctpclient.c -lsctp -o client; and to run, use the following code:

$ ./server &
$  ./client

I’m wrapping up the series for now, but will keep adding more to the topic, on and off.

 

The Socket API, Part 5: SCTP的更多相关文章

  1. Creating Your Own Server: The Socket API, Part 1

    转:http://www.linuxforu.com/2011/08/creating-your-own-server-the-socket-api-part-1/ By Pankaj Tanwar  ...

  2. Creating Your Own Server: The Socket API, Part 2

    转:http://www.linuxforu.com/2011/09/creating-your-own-server-the-socket-api-part-2/ By Pankaj Tanwar  ...

  3. UNIX网络编程——SOCKET API和TCP STATE的对应关系_三次握手_四次挥手及TCP延迟确认

    在socket系统调用中,如何完成三次握手和四次挥手: SOCK_DGRAM即UDP中的connect操作知识在内核中注册对方机器的IP和PORT信息,并没有建立连接的过程,即没有发包,close也不 ...

  4. c/c++ socket API 调用后的错误判断 perror errno

    socket API 调用后的错误判断 perror errno 调用完socket API后,需要判断调用是否成功与失败.如果失败,会自动设置errno(是个整数), 并且用perror可以打印出具 ...

  5. JNI 和 socket api

    1.JavaVM 和 JNIEnvJNIEnv是一个与线程相关的变量,不同线程的JNIEnv彼此独立.JavaVM是虚拟机在JNI层的代表,在一个虚拟机进程中只有一个JavaVM,因此该进程的所有线程 ...

  6. LwIP - raw/callback API、协议栈API(sequential API)、BSD API(或者说 SOCKET API)

    1.使用raw/callback API编程,用户编程的方法是向内核注册各种自定义的回调函数,回调函数是与内核实现交换的唯一方式. recv_udp, accept_function, sent_tc ...

  7. socket编程 ------ BSD socket API

    伯克利套接字(Berkeley sockets),也称为BSD Socket.伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信. BSD Socket的应用 ...

  8. Python Socket API 笔记

    将上节中的C#该成Python版的容易程度大大超出了我的意料之外.从来没有发现,仅仅用灰尘简单的几句话就实现了该程序的主要功能,可见python的简易和强大之处.这里先对SocketAPI 做一下总结 ...

  9. TCP协议和socket API 学习笔记

    本文转载至 http://blog.chinaunix.net/uid-16979052-id-3350958.html 分类:  原文地址:TCP协议和socket API 学习笔记 作者:gilb ...

随机推荐

  1. cocos2d 设置按钮不可用

    需要两步设置按钮变灰,然后不可点击 btnBuy.setBright(false); btnBuy.setTouchEnabled(false); 或者直接不显示按钮 btnBuy.setEnable ...

  2. 【转】Hive学习路线图

    原文博客出自于:http://blog.fens.me/hadoop-hive-roadmap/ 感谢! Hive学习路线图 Hadoop家族系列文章,主要介绍Hadoop家族产品,常用的项目包括Ha ...

  3. 记拿到鹅厂前端开发暑期实习offer的经历

    #想起来时的路 在真正拿到腾讯实习offer之前,也是看过不少人的面经,心生向往.很早在入前端坑之前,我就想着大四的时候有机会要尝试去腾讯里实习. 大一入门语言就是C++,这让我很无奈,所以我很快的就 ...

  4. MYSQL数据库性能调优之六:备份

    增量备份

  5. C#UDP同步实例

    差不多有一个礼拜总算有点进步. 代码很简单,只是为了实现功能. 网络上的资源是很多,除了不能用的,就是抄来抄去,是在乏味浪费时间. 说一下代码背景:实现的功能是发送端发送消息,接收端接收后立即响应,发 ...

  6. Java中的多线程操作初探

    问题引出: 说是java,其实还是在做android的时候遇到的问题,在android 4.0以后,访问网络必须在新线程中实现,所以才会遇到这个问题.只是为了方面说明问题,才新建一个java项目.在m ...

  7. leetcode:Path Sum (路径之和) 【面试算法题】

    题目: Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up ...

  8. 如何在我们项目中利用开源的图表(js chart)

            最近觉得应该把自己在技术上的一些心得记录在博客里面跟大家分享,一起讨论,一起成长!       这篇随笔主要为介绍chart在项目中的运用,因为在我们看到一些开源的chart时候,是使 ...

  9. Git版本管理:Windows下Git配置与使用指南

    简要介绍:Git是一个开源的分布式版本控制系统,用以有效.高速的处理从很小到非常大的项目版本管理. 一.安装 软件:msysGit-fullinstall-1.8.1.2 打开之后设置安装路径,默认为 ...

  10. 用CSS让字体在一行内显示不换行(收藏)

    当一行文字超过DIV或者Table的宽度的时候,浏览器中默认是让它换行显示的,如果不想让他换行要怎么办呢? 用CSS让文字在一行内显示不换行的方法   一般的文字截断(适用于内联与块): .text- ...