* @brief Creates a network socket. * * This function creates a socket and returns a file descriptor that can be used for network communication. * * @param domain The communication protocol family (address family) that defines the socket's protocol. * Common values include: * - 'AF_INET': IPv4 * - 'AF_INET6': IPv6 * - 'AF_UNIX': Local
| 629 | * @see connect() Used to connect to a remote host. |
| 630 | */ |
| 631 | int socket(int domain, int type, int protocol) |
| 632 | { |
| 633 | /* create a BSD socket */ |
| 634 | int fd; |
| 635 | int socket; |
| 636 | struct dfs_file *d; |
| 637 | |
| 638 | /* allocate a fd */ |
| 639 | fd = fd_new(); |
| 640 | if (fd < 0) |
| 641 | { |
| 642 | rt_set_errno(-ENOMEM); |
| 643 | |
| 644 | return -1; |
| 645 | } |
| 646 | d = fd_get(fd); |
| 647 | |
| 648 | #ifdef RT_USING_DFS_V2 |
| 649 | d->fops = dfs_net_get_fops(); |
| 650 | #endif |
| 651 | |
| 652 | d->vnode = (struct dfs_vnode *)rt_malloc(sizeof(struct dfs_vnode)); |
| 653 | if (!d->vnode) |
| 654 | { |
| 655 | /* release fd */ |
| 656 | fd_release(fd); |
| 657 | rt_set_errno(-ENOMEM); |
| 658 | return -1; |
| 659 | } |
| 660 | dfs_vnode_init(d->vnode, FT_SOCKET, dfs_net_get_fops()); |
| 661 | |
| 662 | /* create socket and then put it to the dfs_file */ |
| 663 | socket = sal_socket(domain, type, protocol); |
| 664 | if (socket >= 0) |
| 665 | { |
| 666 | d->flags = O_RDWR; /* set flags as read and write */ |
| 667 | |
| 668 | /* set socket to the data of dfs_file */ |
| 669 | d->vnode->data = (void *)(size_t)socket; |
| 670 | } |
| 671 | else |
| 672 | { |
| 673 | /* release fd */ |
| 674 | fd_release(fd); |
| 675 | rt_set_errno(-ENOMEM); |
| 676 | return -1; |
| 677 | } |
| 678 | |
| 679 | return fd; |
| 680 | } |
| 681 | RTM_EXPORT(socket); |
| 682 | |
| 683 | /** |