如何创建TCP套接字使用C至predefined端口连接 [英] How to Create a TCP socket connect using C to a predefined port

查看:115
本文介绍了如何创建TCP套接字使用C至predefined端口连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非常简单的问题。我想测试一个特定的端口是否正在使用或不。对于这一点,我想绑定TCP套接字的端口,如果被拒绝的连接意味着端口正在使用中,如果不是意味着该端口是免费的。

I have a very simple question. I want to test whether a particular port is currently under use or not. For this, I want to bind a TCP socket to the port, if the connection is refused means the port is in use and if not that mean the port is free.

有人可以告诉我,我怎么能写在C TCP套接字code?我在Solaris平台。

Can someone please tell me how can I write the TCP socket code in C? I am on a solaris platform.

我知道它很基本的。但我AP preciate你的帮助。先谢谢了。

I know its very basic. But I appreciate your help. Thanks in advance.

推荐答案

绑定函数的调用将返回-1,如果有一个错误。这包括如果该地址已在使用。

The call to bind function will return -1 if there is an error. This includes if the address is already in use.

struct sockaddr_in sin;
int socket;

socket = socket(AF_INET, SOCK_STREAM, 0));
if(socket == -1)
{
    printf("error opening socket");
    return -1;
}

sin.sin_port = htons(port);
sin.sin_addr.s_addr = 0;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_family = AF_INET;

if(bind(socket, (struct sockaddr *)&sin,sizeof(struct sockaddr_in) ) == -1)
{
    printf("error binding socket");
    return -1;
}

这篇关于如何创建TCP套接字使用C至predefined端口连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆