Господа, помогите разобраться с ошибкой.
Суть проблемы: программа слушает трафик,что-то вроде сниффера, так вот функция ioctlsocket() выдает ошибку 10042:Bad protocol option.
А так как опыта работы с винсокетами у меня практически нет, то не могу понять в чем проблема.
Ниже привожу текст программы.
Код: Выделить всё
Global Data
include('Winsock.inc')
sock SOCKET
Prmod ULONG
sopt ULONG
code
err#=WSACleanUP()
clear(PWSAData)
if WSAStartup(s32_Version2_0,address(PWSAData))<>0
Message('Error wsastartup:'&WSAGetLastError())
end
Sock=Createsocket(AF_INET,SOCK_STREAM,IPPROTO_IP)
IF Sock < 0
Message('Error createsocket - '&WSAGetLastError())
ELSE
sopt=True
if setsockopt(Sock,SOL_SOCKET,SO_REUSEADDR,address(sopt),size(sopt))<>0
Message('Setsockopt error - '&WSAGetLastError())
else
s_in.sin_family = AF_INET
s_in.sin_addr.s_addr = INADDR_ANY
end
END
if BindSocket(Sock,address(s_in),Size(s_in))= SOCKET_ERROR Message('Error bindsocket - '&WSAGetLastError())
CloseSocket(Sock)
end
PrMod=1
if ioctlsocket(Sock,SIO_RCVALL,PrMod) <> 0
Message('Error - '&WSAGetLastError()) ! здесь выдет ошибку 10042
CloseSocket(Sock)
err#=WSACleanUP()
end
!здесь буду принимать данные
!
CloseSocket(Sock)
err#=WSACleanUP()
!!!!!!!!!!!!!!!!!!!!!!!!
файл winsock.inc
OMIT('_EndOfInclude_',_WINSOCK_)
_WINSOCK_ EQUATE(1)
INCLUDE('WINDOWS.INC'),ONCE
WSAData GROUP,TYPE
wVersion SHORT
wHighVersion SHORT
szDescription CSTRING(WSADESCRIPTION_LEN + 1)
szSystemStatus CSTRING(WSASYS_STATUS_LEN + 1)
iMaxSockets UNSIGNED
iMaxUdpDg UNSIGNED
lpVendorInfo LONG
END
PWSAData LIKE(WSAData)
in_addr GROUP,TYPE
s_b1 BYTE
s_b2 BYTE
s_b3 BYTE
s_b4 BYTE
S_addr LONG
END
SOCKADDR_IN GROUP,TYPE
sin_family SHORT
sin_port USHORT
!sin_addr LIKE(in_addr),pre(sin)
sin_addr LIKE(in_addr)
sin_zero STRING(8)
END
s_in LIKE(SOCKADDR_IN)
SOCKET_ERROR EQUATE(-1)
s32_Version2_0 EQUATE(1000000010b)
INADDR_ANY EQUATE(0)
SIO_RCVALL EQUATE(98000001h)
SOCKET EQUATE(LONG)
SOCK_STREAM EQUATE(1)
IPPROTO_IP EQUATE(0)
AF_INET EQUATE(2)
SOL_SOCKET EQUATE(0ffffh)
SO_REUSEADDR EQUATE(04h)
MAP
MODULE('WinApi')
WSAStartup PROCEDURE(SHORT wVersionRequested, LONG lpWSAData),SIGNED,PASCAL
WSACleanup PROCEDURE(),SIGNED,PASCAL
WSAGetLastError PROCEDURE(),SIGNED,PASCAL,NAME('WSAGetLastError')
CreateSocket PROCEDURE(SIGNED af, SIGNED type, SIGNED protocol),SOCKET,PASCAL,NAME('socket')
CloseSocket PROCEDURE(SOCKET s),SIGNED,PROC,PASCAL,NAME('closesocket')
ReceiveData PROCEDURE(SOCKET s, LONG lpstrBuffer, SIGNED dwLen, SIGNED flags),SIGNED,PASCAL,NAME('recv')
BindSocket PROCEDURE(SOCKET s, LONG lpname, SIGNED namelen),SIGNED,RAW,PASCAL,NAME('bind')
Listen PROCEDURE(SOCKET s, SIGNED backlog),SIGNED,PASCAL,NAME('listen')
setsockopt PROCEDURE(SOCKET s, SIGNED level, SIGNED optname, LONG lpszOptVal, SIGNED optlen),SIGNED,PASCAL
Ioctlsocket PROCEDURE(SOCKET s,LONG,*ULONG),SHORT,RAW,PASCAL,NAME('IOCTLSOCKET')
END
end
_EndOfInclude_
На компе стоит WinXP Professional SP2,Clarion 6.1.
Заранее благодарна,
Анна.
Господа, помогите разобраться с ошибкой.
Суть проблемы: программа слушает трафик,что-то вроде сниффера, так вот функция ioctlsocket() выдает ошибку 10042:Bad protocol option.
А так как опыта работы с винсокетами у меня практически нет, то не могу понять в чем проблема.
Ниже привожу текст программы.
Код: Выделить всё
Global Data
include('Winsock.inc')
sock SOCKET
Prmod ULONG
sopt ULONG
code
err#=WSACleanUP()
clear(PWSAData)
if WSAStartup(s32_Version2_0,address(PWSAData))<>0
Message('Error wsastartup:'&WSAGetLastError())
end
Sock=Createsocket(AF_INET,SOCK_STREAM,IPPROTO_IP)
IF Sock < 0
Message('Error createsocket - '&WSAGetLastError())
ELSE
sopt=True
if setsockopt(Sock,SOL_SOCKET,SO_REUSEADDR,address(sopt),size(sopt))<>0
Message('Setsockopt error - '&WSAGetLastError())
else
s_in.sin_family = AF_INET
s_in.sin_addr.s_addr = INADDR_ANY
end
END
if BindSocket(Sock,address(s_in),Size(s_in))= SOCKET_ERROR Message('Error bindsocket - '&WSAGetLastError())
CloseSocket(Sock)
end
PrMod=1
if ioctlsocket(Sock,SIO_RCVALL,PrMod) <> 0
Message('Error - '&WSAGetLastError()) ! здесь выдет ошибку 10042
CloseSocket(Sock)
err#=WSACleanUP()
end
!здесь буду принимать данные
!
CloseSocket(Sock)
err#=WSACleanUP()
!!!!!!!!!!!!!!!!!!!!!!!!
файл winsock.inc
OMIT('_EndOfInclude_',_WINSOCK_)
_WINSOCK_ EQUATE(1)
INCLUDE('WINDOWS.INC'),ONCE
WSAData GROUP,TYPE
wVersion SHORT
wHighVersion SHORT
szDescription CSTRING(WSADESCRIPTION_LEN + 1)
szSystemStatus CSTRING(WSASYS_STATUS_LEN + 1)
iMaxSockets UNSIGNED
iMaxUdpDg UNSIGNED
lpVendorInfo LONG
END
PWSAData LIKE(WSAData)
in_addr GROUP,TYPE
s_b1 BYTE
s_b2 BYTE
s_b3 BYTE
s_b4 BYTE
S_addr LONG
END
SOCKADDR_IN GROUP,TYPE
sin_family SHORT
sin_port USHORT
!sin_addr LIKE(in_addr),pre(sin)
sin_addr LIKE(in_addr)
sin_zero STRING(8)
END
s_in LIKE(SOCKADDR_IN)
SOCKET_ERROR EQUATE(-1)
s32_Version2_0 EQUATE(1000000010b)
INADDR_ANY EQUATE(0)
SIO_RCVALL EQUATE(98000001h)
SOCKET EQUATE(LONG)
SOCK_STREAM EQUATE(1)
IPPROTO_IP EQUATE(0)
AF_INET EQUATE(2)
SOL_SOCKET EQUATE(0ffffh)
SO_REUSEADDR EQUATE(04h)
MAP
MODULE('WinApi')
WSAStartup PROCEDURE(SHORT wVersionRequested, LONG lpWSAData),SIGNED,PASCAL
WSACleanup PROCEDURE(),SIGNED,PASCAL
WSAGetLastError PROCEDURE(),SIGNED,PASCAL,NAME('WSAGetLastError')
CreateSocket PROCEDURE(SIGNED af, SIGNED type, SIGNED protocol),SOCKET,PASCAL,NAME('socket')
CloseSocket PROCEDURE(SOCKET s),SIGNED,PROC,PASCAL,NAME('closesocket')
ReceiveData PROCEDURE(SOCKET s, LONG lpstrBuffer, SIGNED dwLen, SIGNED flags),SIGNED,PASCAL,NAME('recv')
BindSocket PROCEDURE(SOCKET s, LONG lpname, SIGNED namelen),SIGNED,RAW,PASCAL,NAME('bind')
Listen PROCEDURE(SOCKET s, SIGNED backlog),SIGNED,PASCAL,NAME('listen')
setsockopt PROCEDURE(SOCKET s, SIGNED level, SIGNED optname, LONG lpszOptVal, SIGNED optlen),SIGNED,PASCAL
Ioctlsocket PROCEDURE(SOCKET s,LONG,*ULONG),SHORT,RAW,PASCAL,NAME('IOCTLSOCKET')
END
end
_EndOfInclude_
На компе стоит WinXP Professional SP2,Clarion 6.1.
Заранее благодарна,
Анна.
- Remove From My Forums
-
Question
-
When creating a TcpListener object I am getting error code 10042. Below is the code I am using.
IPHostEntry localMachineInfo = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(localMachineInfo.AddressList[0], System.Convert.ToInt32(tbPort.Text));
TcpListener listener = new TcpListener(localEP);
listener.Start();
When debugging this code I notice that right after listener object is created I see error code 10042 (An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call).
am I missing a configuration setup ?
Answers
-
You are welcome
,
If you feel my replies helped you in your problem. Please mark as Answered.
Best Regards,
Rizwan aka RizwanSharp
So I am getting started with SCTP and have written the basics of the SCTP server application(which I intend to modify to make it a peer-to-peer app). The code is incomplete but I compiled and ran it to test the socket options and the first setsockopt returns error 10042(protocol not supported). I have determined that it’s the first call of setsockopt() that returns an error. So here is the incomplete code:
#include "stdafx.h"
#include <iostream>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#ifndef UNICODE
#define UNICODE
#endif
#define WIN32_LEAN_AND_MEAN
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <WS2spi.h>
#include <ws2sctp.h>
#include <wsipv6ok.h>
#include <if.h>
#include "ws2isatap.h"
#include "if_tunnel.h"
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "sctpsp.lib")
using namespace std;
using namespace System;
static int LISTENQ = 5;
void isatap_enable(void);
int main(int argc, char* argv[]){
WSADATA wsaData;
int iResult;
int optv = 10;
u_long imode = 1;
bool connected = false;
char *optval = (char*)&optv;
int optlen = sizeof(optval);
sockaddr_in6 servAddr;
sctp_sndrcvinfo sr;
sctp_event_subscribe evnts;
sctp_initmsg init;
memset(&sr,0,sizeof(sr));
memset(&evnts,0,sizeof(evnts));
memset(&init,0,sizeof(init));
memset(&servAddr,0,sizeof(servAddr));
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != NO_ERROR) {
wprintf(L"WSAStartup function failed with error: %dn", iResult);
return 1;
}
SOCKET servSock = socket(AF_INET6,SOCK_STREAM,IPPROTO_SCTP);
if(servSock==INVALID_SOCKET){
printf("Socket function failed with error: %dn",GetLastError());
return 1;
}
if(setsockopt(servSock,IPPROTO_IPV6,IPV6_PROTECTION_LEVEL,optval,sizeof(optval))<0){
printf("setsockopt function failed with error: %dn", GetLastError());
return 1;
}
u_int servPort = 5000;
servAddr.sin6_family = AF_INET6;
servAddr.sin6_addr = in6addr_any;
servAddr.sin6_port = htons(servPort);
if(setsockopt(servSock,IPPROTO_SCTP,SCTP_EVENTS,(const char*)&evnts,sizeof(evnts)) < 0){
printf("setsockopt function failed with error: %dn", GetLastError());
return 1;
}
ioctlsocket(servSock,FIONBIO, &imode);
if(bind(servSock,(struct sockaddr*)&servAddr,sizeof(servAddr))<0){
printf("Bind function failed with error: %dn", GetLastError());
return 1;
}
evnts.sctp_data_io_event = 1;
evnts.sctp_association_event = *(u_char*)optval;
for(;;){
if(listen(servSock,LISTENQ) < 0){
printf("Listen function failed with error: %d/n",GetLastError());
return 1;
}else{
printf("Listening on port %dn",servPort);
}
}
}
Я пытаюсь прослушать сокет с помощью многоадресной рассылки, но кажется, что я плохо использую функцию setsockopt
. Я искал значение кода ошибки 10042 и нашел https://learn.microsoft.com/windows/win32/winsock/windows-sockets-error-codes-2, но я не понимаю объяснения.
Вот моя функция, где я создаю сокет для прослушивания порта внутри многоадресной группы:
/* Includes */
#include <windows.h>
#include <winsock.h>
#include <iostream>
#include <cstdlib>
#pragma comment (lib, "Ws2_32.lib")
/* Defines */
#define BUFLEN 1024
#define MULTICAST_GROUP "225.30.8.1"
#define LOCAL_IP "192.168.6.200"
#define DEFAULT_FTI_PORT 8600
/* Structs */
typedef struct {
uint32_t receive_data[BUFLEN]; // receive data
}comm_data_t;
typedef struct {
SOCKET sockfd; // RX socket ID
int long_dir; // size of address
struct sockaddr_in socket_addr; // client socket struct
struct sockaddr_in socket_sender; // sender socket struct
comm_data_t data; // data struct
}socket_t;
socket_t socket_info;
/* Returns 1 if succesfull, 0 otherwise */
uint8_t createSocket(void)
{
WSADATA wsaData;
struct ip_mreq mreq; // multicast
int iResult;
cout << "IP: " << LOCAL_IP << endl;
cout << "MULTICAST GROUP: " << MULTICAST_GROUP << endl;
cout << "PORT: " << DEFAULT_FTI_PORT << endl << endl;
// Initialize Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("[SOCKET] WSAStartup failed with error: %dn", iResult);
return 0;
}
memset(&socket_info.socket_addr, 0, sizeof(socket_info.socket_addr));
socket_info.socket_addr.sin_family = AF_INET;
socket_info.socket_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socket_info.socket_addr.sin_port = htons(DEFAULT_FTI_PORT);
socket_info.long_dir = sizeof(socket_info.socket_sender);
// Create a new socket to make a client connection.
if ((socket_info.sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
{
printf("[SOCKET] socket() failed! Error code: %ldn", WSAGetLastError());
WSACleanup();
return 0;
}
else
printf("[SOCKET] socket() is OK!n");
if (bind(socket_info.sockfd, (struct sockaddr*) &socket_info.socket_addr, sizeof(socket_info.socket_addr)) < 0)
{
printf("[SOCKET] bind() failed! Error code: %ldn", WSAGetLastError());
return 0;
}
else
printf("[SOCKET] bind() is OK!n");
// Set multicast option
mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_GROUP);
mreq.imr_interface.s_addr = inet_addr(LOCAL_IP);
if ( (setsockopt(socket_info.sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char*) &mreq, sizeof(mreq))) < 0)
{
printf("[SOCKET] setsockopt() failed! Error code: %ldn", WSAGetLastError());
return 0;
}
else
printf("[SOCKET] setsockopt() is OK!n");
return 1;
}
А затем у меня есть еще одна функция, где я читаю полученные данные:
/* Returns number of bytes received */
uint8_t readFromSocket(void)
{
int32_t BytesReceived = 0;
/* RECEIVE DATA */
BytesReceived = recvfrom(socket_info.sockfd, (char*) &socket_info.data.receive_data,
BUFLEN, 0,
(struct sockaddr*) &socket_info.socket_sender,
&socket_info.long_dir);
if (BytesReceived < 0)
{
printf("[SOCKET] recvfrom() error %ld.n", WSAGetLastError());
return 0;
}
else
return BytesReceived ;
}
Кажется, я не могу присоединиться к многоадресной группе, но я не знаю, где я терплю неудачу.
Я использую протокол UDP, поэтому, если я изменю параметр setsockopt
IPPROTO_IP на IPPROTO_UDP, я получу код ошибки 10022.
Что означают эти ошибки и как я могу сделать это правильно?
2 ответа
Вы используете старый набор включаемых файлов. Вместо этого:
#include <windows.h>
#include <winsock.h>
Использовать это:
#include <winsock2.h>
#include <ws2tcpip.h>
И он должен работать как положено.
0
dbush
22 Дек 2022 в 05:48
Я нашел решение самостоятельно.
Я использую другой родной .lib из Windows.
Раньше в моем заголовочном файле у меня было:
#pragma comment (lib, "Ws2_32.lib")
Но теперь я использую другой .lib. Это библиотека, которую я использую прямо сейчас и работает для меня:
#pragma comment (lib, "wsock32.lib")
Я полагаю, что это вопрос дистрибутива моей ОС.
В любом случае большое спасибо за ваши комментарии.
0
Londo
22 Дек 2022 в 11:20
Error 10042 is often a critical system error caused by corrupt and missing registry data. This error should be fixed immediately to prevent further damage to the Windows file system. Download Error 10042 Repair Tool
Your PC Health Report
Scan Time: | Error 10042 Problems: Detected | |||
Operating System: | System Performance: Not Optimized | |||
Screen Resolution: | Registry Errors: Detected | |||
Browser Type: | Danger Level: High |
Error 10042 error symptoms can include slow PC performance, program crashes, system freezes, startup/shutdown problems, and file errors. Risks that can result from not repairing your computer include blue screens, file corruption, and hardware failure.
Fixing Error 10042 is easy. Download and install Advanced System Repair, a Microsoft Windows tool that will analyze your registry for missing, obsolete, and corrupt entries resulting from failed installations, incomplete un-installations, disabled drivers, and spyware applications. Click on the link below for your free download.
Download Error 10042 Repair Tool
*Advanced System Repair will repair Error 10042 and registry data errors on your PC
Instructions
Step 1:
Download & run Advanced System Repair.
Step 2:
Click the «Scan» button.
Step 3:
Click the ‘Fix Errors’ Button to Repair Your PC!
Problem Description:
I am trying to set keep alive times on a connected socket and getting following exception
System.Net.Sockets.SocketException (10042): An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Int32 optionValue)
at System.Net.Sockets.SocketExtensions.SetKeepAlive(Socket socket, Boolean keepAlive, Int32 keepAliveTime, Int32 keepAliveInterval, Int32 keepAliveRetryCount)
at ServerService.Service.OnManagerConnection(IConnection sender, Socket socket)
This is the code that is being called
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 1);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 5);
The exception is only thrown on Windows Server 2016, same code works on other Windows versions and linux.
Hope someone can shed some light where the problem could be.
Solution – 1
Two of these options are not supported before Windows 1709, namely TcpKeepAliveTime
and TcpKeepAliveInterval
. And TcpKeepAliveRetryCount
is only available beginning 1703. Windows Server 2016 is equivalent to Windows 10 version 1607.
The Winsock documentation says under the TCP_KEEPIDLE
and TCP_KEEPINTVL
options:
«This option is available starting with Windows 10, version 1709.»
And for TCP_KEEPCNT
it says:
Starting with Windows 10, version 1703
You will therefore just have to use a try
catch
as there appears to be no way to check supported options.
I am trying to set keep alive times on a connected socket and getting following exception
System.Net.Sockets.SocketException (10042): An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call.
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Int32 optionValue)
at System.Net.Sockets.SocketExtensions.SetKeepAlive(Socket socket, Boolean keepAlive, Int32 keepAliveTime, Int32 keepAliveInterval, Int32 keepAliveRetryCount)
at ServerService.Service.OnManagerConnection(IConnection sender, Socket socket)
This is the code that is being called
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 1);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 5);
The exception is only thrown on Windows Server 2016, same code works on other Windows versions and linux.
Hope someone can shed some light where the problem could be.
>Solution :
Two of these options are not supported before Windows 1709, namely TcpKeepAliveTime
and TcpKeepAliveInterval
. And TcpKeepAliveRetryCount
is only available beginning 1703. Windows Server 2016 is equivalent to Windows 10 version 1607.
The Winsock documentation says under the TCP_KEEPIDLE
and TCP_KEEPINTVL
options:
«This option is available starting with Windows 10, version 1709.»
And for TCP_KEEPCNT
it says:
Starting with Windows 10, version 1703
You will therefore just have to use a try
catch
as there appears to be no way to check supported options.
- Remove From My Forums
-
Question
-
When creating a TcpListener object I am getting error code 10042. Below is the code I am using.
IPHostEntry localMachineInfo = Dns.GetHostEntry(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(localMachineInfo.AddressList[0], System.Convert.ToInt32(tbPort.Text));
TcpListener listener = new TcpListener(localEP);
listener.Start();
When debugging this code I notice that right after listener object is created I see error code 10042 (An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call).
am I missing a configuration setup ?
Answers
-
You are welcome
,
If you feel my replies helped you in your problem. Please mark as Answered.
Best Regards,
Rizwan aka RizwanSharp