Sockets 用于HTTP通信的套接字TCP/IP
下面的代码是用于socket教程的php代码示例,我成功运行以收集远程站点或本地主机网页。我用于socket_创建的协议号为0或6,两者都是 number也在编写代码,为什么?我认为网络编程将需要包括TCP和IP,用于今天的Windows计算机,以使通信成为可能。为什么只需要TCP或IP协议num就可以使程序代码工作,而不包括这两个协议num? TCP是OSI或经典TCP/IP模型的传输层协议,IP是网络层协议Sockets 用于HTTP通信的套接字TCP/IP,sockets,network-programming,tcp-ip,Sockets,Network Programming,Tcp Ip,下面的代码是用于socket教程的php代码示例,我成功运行以收集远程站点或本地主机网页。我用于socket_创建的协议号为0或6,两者都是 number也在编写代码,为什么?我认为网络编程将需要包括TCP和IP,用于今天的Windows计算机,以使通信成为可能。为什么只需要TCP或IP协议num就可以使程序代码工作,而不包括这两个协议num? TCP是OSI或经典TCP/IP模型的传输层协议,IP是网络层协议 <?php $prot
<?php
$protocol = 'tcp';
$get_prot = getprotobyname($protocol);
echo $get_prot."----protocol\n";
if(!($sock = socket_create(AF_INET, SOCK_STREAM, 6)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg \n");
}
echo "Socket created \n";
if(!socket_connect($sock , '127.0.0.1' , 80))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not connect: [$errorcode] $errormsg \n");
}
echo "Connection established \n";
$message = "GET / HTTP/1.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 \r\n\r\n";
$message = "GET / HTTP/1.1\r\n";
$message .= "Host: \r\n";
$message .= "Connection: Close\r\n\r\n";
//Send the message to the server
if( ! socket_send ( $sock , $message , strlen($message) , 0))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not send data: [$errorcode] $errormsg \n");
}
echo "Message send successfully \n";
//Now receive reply from server
if(socket_recv ( $sock , $buf , 6144 , MSG_WAITALL ) === FALSE)
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Could not receive data: [$errorcode] $errormsg \n");
}
//print the received message
echo $buf;
?>
将0作为协议传递将为您提供默认协议。AF_INET说你想要 IP协议套件(特别是IPv4)。对于AF_INET和SOCK_STREAM的组合,tcp是默认值。AF_INET6和SOCK_DGRAM的组合将为您提供默认的IPv6和UDP
TCP有第6号协议,如果您想明确说明,也可以传递该协议。否,谢谢您的回复。我的问题是,为什么两者都可以工作0(IPv4)或6(TCP),我认为TCP和IP需要一起工作以实现通信,请建议,请再次查看我的问题,有关socket_创建的手册,请访问以下网站advise@aabb我不明白你还问什么。我已经告诉过你0的意思了。0并不意味着IPv4。1。参数,AF_INET表示IPv4。感谢您的回复,0表示依赖于计算机默认值的默认协议,例如,窗口上的协议默认值是TCP,对吗?是的,TCP是几乎任何操作系统上AF_INET和SOCK_流组合的默认值。