本文主要是介绍VC++ 设置网卡接口MTU大小,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在 Windows C/C++ 之中一共有三种方法可以设置网卡的MTU大小。
方法一:
SetIpInterfaceEntry 法
static bool SetInterfaceMtu2(int interface_index, int mtu) noexcept{PIP_ADAPTER_ADDRESSES pAddresses = NULL;ULONG ulBufLen = 0;GetAdaptersAddresses(AF_UNSPEC, 0, NULL, pAddresses, &ulBufLen);char* szBuf = (char*)Malloc(ulBufLen);pAddresses = (IP_ADAPTER_ADDRESSES*)szBuf;if (NULL == pAddresses){return false;}NETIOAPI_API dwErr = GetAdaptersAddresses(AF_INET, GAA_FLAG_SKIP_ANYCAST, NULL, pAddresses, &ulBufLen);if (dwErr == NO_ERROR){while (NULL != pAddresses){if (pAddresses->IfIndex == interface_index) {MIB_IPINTERFACE_ROW ifRow;InitializeIpInterfaceEntry(&ifRow);//interested nameifRow.InterfaceLuid = pAddresses->Luid;ifRow.Family = AF_INET;ifRow.NlMtu = mtu;dwErr = SetIpInterfaceEntry(&ifRow);break;}pAddresses = pAddresses->Next;}}Mfree(szBuf);return dwErr == NO_ERROR;}
方法二:
SetIfEntry 法
std::shared_ptr<MIB_IFROW> GetIfEntry(int interface_index) noexcept{if (interface_index < 0){return NULL;}std::shared_ptr<MIB_IFROW> pIfRow = std::shared_ptr<MIB_IFROW>((MIB_IFROW*)Malloc(sizeof(MIB_IFROW)),[](MIB_IFROW* p) noexcept{Mfree(p);});if (NULL == pIfRow){return NULL;}pIfRow->dwIndex = interface_index;if (::GetIfEntry(pIfRow.get()) != NO_ERROR){return NULL;}return pIfRow;}int GetInterfaceMtu(int interface_index) noexcept{std::shared_ptr<MIB_IFROW> ifRow = GetIfEntry(interface_index);if (NULL == ifRow){return -1;}else{return ifRow->dwMtu;}}bool SetInterfaceMtu(int interface_index, int mtu) noexcept{// https://learn.microsoft.com/en-us/windows/win32/api/netioapi/nf-netioapi-getifentry2// https://learn.microsoft.com/en-us/windows/win32/api/iphlpapi/nf-iphlpapi-getifentrystd::shared_ptr<MIB_IFROW> ifRow = GetIfEntry(interface_index);if (NULL == ifRow){return false;}if (ifRow->dwMtu == mtu){return true;}else{ifRow->dwMtu = mtu;}DWORD dwErr = SetIfEntry(ifRow.get());if (dwErr == NO_ERROR){if (GetInterfaceMtu(interface_index) == mtu){return true;}}return SetInterfaceMtu2(interface_index, mtu);}
方法三:
命令行法
查看网络接口设置(MTU列项)
netsh interface ipv4 show subinterfaces
通过网络接口索引来管理,MTU是大小,10为网络接口索引
netsh interface ipv4 set subinterface 10 mtu=1400 store=persistent
通过网络接口名字来管理,MTU是大小,eth0为网络接口名
netsh interface ipv4 set subinterface eth0 mtu=1400 store=persistent
这篇关于VC++ 设置网卡接口MTU大小的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!