织梦CMS - 轻松建站从此开始!

罗索

socket相关常用函数

落鹤生 发布于 2012-05-07 09:14 点击:次 
socket相关的几个常用函数
TAG:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>

/****************************************************************************
*Description:
*    it is used to connect to specified host with socket.
*
*Parameters:
*    hostname:    host name
*    port:        port
*    sockfd:        socket handle returned if success
*
*Returns:
*    return 0 if success, 1 i failed.
*
****************************************************************************/
int sock_connect(char *hostname, int port, int *sockfd)
{
char tmpbuf[64];
int  sfd = 0;
struct sockaddr_in addr;
struct hostent *ph = 0;

    ph = gethostbyname(hostname);
    if ( ph == NULL ) {
        strcpy(tmpbuf, hostname);
    } else {
        strcpy(tmpbuf, (char*)inet_ntoa(*(struct in_addr*)ph->h_addr_list[0]));
    }

    addr.sin_family            = AF_INET;
    addr.sin_port            = htons(port);
    addr.sin_addr.s_addr    = inet_addr(tmpbuf);
    if(addr.sin_addr.s_addr == INADDR_NONE) {
        return 1;
    }

    sfd = socket(AF_INET,SOCK_STREAM,0);
    if ( sfd < 0 ) {
        return 1;
    }
     if ( connect(sfd, (struct sockaddr *)&addr, sizeof(addr)) ) {
        return 1;
    }
    *sockfd = sfd;

    return 0;
}

/****************************************************************************
*Description:
*    it is used to get local ipaddress.
*
*Parameters:
*    eth:    device name, eg: "eth0"
*    ipaddr:    ipaddress returned if success
*
*Returns:
*    return 0 if success, 1 if failed.
*
****************************************************************************/
int sock_ipaddr(char *eth, char *ipaddr)
{
struct ifreq req;
struct sockaddr_in *addr;
unsigned long ip = 0;
int sock = 0;

    if ( (!eth) || (!ipaddr) ) {
        return 1;
    }

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if ( sock < 0 ) {
        return 1;
    }

    strcpy(req.ifr_name, eth);
    if ( ioctl(sock,SIOCGIFADDR,&req) == -1 ) {
        return 1;
    }
    addr = (struct sockaddr_in *)&req.ifr_addr;
    ip = addr->sin_addr.s_addr;
    sprintf(ipaddr, "%d.%d.%d.%d", ip&0xff, (ip>>8)&0xff, (ip>>16)&0xff, (ip>>24)&0xff);

    return 0;
}

(stavy.sun)
本站文章除注明转载外,均为本站原创或编译欢迎任何形式的转载,但请务必注明出处,尊重他人劳动,同学习共成长。转载请注明:文章转载自:罗索实验室 [http://www.rosoo.net/a/201205/15981.html]
本文出处:blog.chinaunix.net 作者:stavy.sun 原文
顶一下
(0)
0%
踩一下
(0)
0%
------分隔线----------------------------
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 验证码:点击我更换图片
栏目列表
将本文分享到微信
织梦二维码生成器
推荐内容