使用#pragma阻止一些warnings

本文详细解读了C++编译器产生的各种警告信息及其含义,帮助开发者理解并解决常见的编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这篇博客的内容都是记的网上的。是流水账。只是记录下来以便日后之有,避免每次重新google。

#pragma除了可以用来把不同功能的代码进行分隔组织外还可以用来disable一些warnings。这在引入一些第三方带有warnings的库的时候很有用。

#pragma用处:http://nshipster.com/pragma/

#Clang Diagnostics: http://nshipster.com/clang-diagnostics/

Clang warning strings和flag的对应表:http://fuckingclangwarnings.com/

为防止以后这个fuckingclangwarnings不能再打开记之如下:


Semantic Warnings

WarningMessage
-WCFString-literalinput conversion stopped due to an input byte that does not belong to the input codeset UTF-8
-WNSObject-attribute__attribute ((NSObject)) may be put on a typedef only, attribute is ignored
-Wabstract-vbase-initinitializer for virtual base class %0 of abstract class %1 will never be used
-Waddress-of-array-temporarypointer is initialized by a temporary array, which will be destroyed at the end of the full-expression
-Warc-maybe-repeated-use-of-weak"weak %select{variable|property|implicit property|instance variable}0 %1 may be accessed multiple times in this %select{function|method|block|lambda}2 and may be unpredictably set to nil assign to a strong variable to keep the object alive
-Warc-non-pod-memaccess%select{destination for|source of}0 this %1 call is a pointer to ownership-qualified type %2
-Warc-performSelector-leaksperformSelector may cause a leak because its selector is unknown
-Warc-repeated-use-of-weak"weak %select{variable|property|implicit property|instance variable}0 %1 is accessed multiple times in this %select{function|method|block|lambda}2 but may be unpredictably set to nil assign to a strong variable to keep the object alive
-Warc-retain-cyclescapturing %0 strongly in this block is likely to lead to a retain cycle
-Warc-unsafe-retained-assignassigning retained object to unsafe property object will be released after assignment
-Warc-unsafe-retained-assignassigning %select{array literal|dictionary literal|numeric literal|boxed expression|should not happen|block literal}0 to a weak %select{property|variable}1 object will be released after assignment
-Warc-unsafe-retained-assignassigning retained object to %select{weak|unsafe_unretained}0 %select{property|variable}1 object will be released after assignment
-Warray-boundsarray index %0 is past the end of the array (which contains %1 element%s2)
-Warray-boundsarray index %0 is before the beginning of the array
-Warray-bounds'static' has no effect on zero-length arrays
-Warray-boundsarray argument is too small contains %0 elements, callee requires at least %1
-Warray-bounds-pointer-arithmeticthe pointer incremented by %0 refers past the end of the array (that contains %1 element%s2)
-Warray-bounds-pointer-arithmeticthe pointer decremented by %0 refers before the beginning of the array
-Wassign-enuminteger constant not in range of enumerated type %0
-Watomic-property-with-user-defined-accessorwritable atomic property %0 cannot pair a synthesized %select{getter|setter}1 with a user defined %select{getter|setter}2
-Wattributesunknown attribute %0 ignored
-Wauto-var-id'auto' deduced as 'id' in declaration of %0
-Wavailabilityunknown platform %0 in availability macro
-Wavailabilityoverriding method %select{introduced after|deprecated before|obsoleted before}0 overridden method on %1 (%2 vs. %3)
-Wavailabilityavailability does not match previous declaration
-Wavailabilityoverriding method cannot be unavailable on %0 when its overridden method is available
-Wavailabilityfeature cannot be %select{introduced|deprecated|obsoleted}0 in %1 version %2 before it was %select{introduced|deprecated|obsoleted}3 in version %4 attribute ignored
-Wbad-function-castcast from function call of type %0 to non-matching type %1
-Wbitfield-constant-conversionimplicit truncation from %2 to bitfield changes value from %0 to %1
-Wbitwise-op-parentheses'&' within '|'
-Wbool-conversion"initialization of pointer of type %0 to null from a constant boolean " "expression
-Wbridge-cast%0 cannot bridge to %1
-Wbridge-cast%0 bridges to %1, not %2
-Wbuiltin-requires-headerdeclaration of built-in function '%0' requires inclusion of the header stdio.h
-Wbuiltin-requires-headerdeclaration of built-in function '%0' requires inclusion of the header setjmp.h
-Wbuiltin-requires-headerdeclaration of built-in function '%0' requires inclusion of the header ucontext.h
-Wc++-compat%select{|empty }0%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++
-Wc++11-compatexplicit instantiation cannot be 'inline'
-Wc++11-compatexplicit instantiation of %0 must occur at global scope
-Wc++11-compatexplicit instantiation of %0 not in a namespace enclosing %1
-Wc++11-compatexplicit instantiation of %q0 must occur in namespace %1
-Wc++11-narrowingconstant expression evaluates to %0 which cannot be narrowed to type %1 in C++11
-Wc++11-narrowingtype %0 cannot be narrowed to %1 in initializer list in C++11
-Wc++11-narrowingnon-constant-expression cannot be narrowed from type %0 to %1 in initializer list in C++11
-Wc++98-c++11-compattype definition in a constexpr %select{function|constructor}0 is incompatible with C++ standards before C++1y
-Wc++98-c++11-compatuse of this statement in a constexpr %select{function|constructor}0 is incompatible with C++ standards before C++1y
-Wc++98-c++11-compatinit-captures.def warn_cxx11_compat_init_capture : Warning "initialized lambda captures are incompatible with C++ standards " "before C++1y
-Wc++98-c++11-compatvariable declaration in a constexpr %select{function|constructor}0 is incompatible with C++ standards before C++1y
-Wc++98-c++11-compatconstexpr function with no return statements is incompatible with C++ standards before C++1y
-Wc++98-c++11-compatmultiple return statements in constexpr function is incompatible with C++ standards before C++1y
-Wc++98-c++11-compatvariable templates are incompatible with C++ standards before C++1y
-Wc++98-compatsubstitution failure due to access control is incompatible with C++98
-Wc++98-compat%select{anonymous struct|union}0 member %1 with a non-trivial %select{constructor|copy constructor|move constructor|copy assignment operator|move assignment operator|destructor}2 is incompatible with C++98
-Wc++98-compatenumeration type in nested name specifier is incompatible with C++98
-Wc++98-compatstatic data member %0 in union is incompatible with C++98
-Wc++98-compatdefault template arguments for a function template are incompatible with C++98
-Wc++98-compatscalar initialized from empty initializer list is incompatible with C++98
-Wc++98-compatbefriending %1 without '%select{struct|interface|union|class|enum}0' keyword is incompatible with C++98
-Wc++98-compatuse of null pointer as non-type template argument is incompatible with C++98
-Wc++98-compatfriend declaration naming a member of the declaring class is incompatible with C++98
-Wc++98-compatnon-class friend type %0 is incompatible with C++98
-Wc++98-compatbefriending enumeration type %0 is incompatible with C++98
-Wc++98-compatuse of non-static data member %0 in an unevaluated context is incompatible with C++98
-Wc++98-compatfriend function %0 would be implicitly redefined in C++98
-Wc++98-compat%select{class template|class template partial|variable template|variable template partial|function template|member function|static data member|member class|member enumeration}0 specialization of %1 outside namespace %2 is incompatible with C++98
-Wc++98-compatreference initialized from initializer list is incompatible with C++98
-Wc++98-compatredundant parentheses surrounding address non-type template argument are incompatible with C++98
-Wc++98-compatinitialization of initializer_list object is incompatible with C++98
-Wc++98-compatuse of 'template' keyword outside of a template is incompatible with C++98
-Wc++98-compatnon-type template argument referring to %select{function|object}0 %1 with internal linkage is incompatible with C++98
-Wc++98-compatuse of 'typename' outside of a template is incompatible with C++98
-Wc++98-compatpassing object of trivial but non-POD type %0 through variadic %select{function|block|method|constructor}1 is incompatible with C++98
-Wc++98-compatgoto would jump into protected scope in C++98
-Wc++98-compatconstructor call from initializer list is incompatible with C++98
-Wc++98-compat'auto' type specifier is incompatible with C++98
-Wc++98-compatdelegating constructors are incompatible with C++98
-Wc++98-compat'constexpr' specifier is incompatible with C++98
-Wc++98-compatinheriting constructors are incompatible with C++98
-Wc++98-compatexplicit conversion functions are incompatible with C++98
-Wc++98-compatswitch case would be in a protected scope in C++98
-Wc++98-compat'%0' type specifier is incompatible with C++98
-Wc++98-compatindirect goto might cross protected scopes in C++98
-Wc++98-compat-pedanticcast between pointer-to-function and pointer-to-object is incompatible with C++98
-Wc++98-compat-pedanticimplicit conversion from array size expression of type %0 to %select{integral|enumeration}1 type %2 is incompatible with C++98
-Wcast-aligncast from %0 to %1 increases required alignment from %2 to %3
-Wcast-of-sel-typecast of type %0 to %1 is deprecated use sel_getName instead
-Wchar-subscriptsarray subscript is of type 'char'
-Wconditional-uninitializedvariable %0 may be uninitialized when %select{used here|captured by block}1
-Wconstant-logical-operanduse of logical '%0' with constant operand
-Wconstexpr-not-const'constexpr' non-static member function will not be implicitly 'const' in C++1y add 'const' to avoid a change in behavior
-Wconsumedstate of variable '%0' must match at the entry and exit of loop
-Wconsumedparameter '%0' not in expected state when the function returns: expected '%1', observed '%2'
-Wconsumedargument not in expected state expected '%0', observed '%1'
-Wconsumedinvalid invocation of method '%0' on a temporary object while it is in the '%1' state
-Wconsumedreturn state set for an unconsumable type '%0'
-Wconsumedconsumed analysis attribute is attached to member of class '%0' which isn't marked as consumable
-Wconsumedinvalid invocation of method '%0' on object '%1' while it is in the '%2' state
-Wconsumedreturn value not in expected state expected '%0', observed '%1'
-Wconversionimplicit conversion discards imaginary component: %0 to %1
-Wconversionnon-type template argument with value '%0' converted to '%1' for unsigned template parameter of type %2
-Wconversionimplicit conversion loses floating-point precision: %0 to %1
-Wconversionimplicit conversion loses integer precision: %0 to %1
-Wconversionnon-type template argument value '%0' truncated to '%1' for template parameter of type %2
-Wconversionimplicit conversion turns vector to scalar: %0 to %1
-Wconversionimplicit conversion turns floating-point number into integer: %0 to %1
-Wcovered-switch-defaultdefault label in switch which covers all enumeration values
-Wcustom-atomic-propertiesatomic by default property %0 has a user defined %select{getter|setter}1 (property should be marked 'atomic' if this is intended)
-Wdangling-fieldinitializing pointer member %0 with the stack address of parameter %1
-Wdangling-fieldbinding reference %select{|subobject of }1member %0 to a temporary value
-Wdangling-fieldbinding reference member %0 to stack allocated parameter %1
-Wdangling-initializer-listarray backing the initializer list will be destroyed at the end of %select{the full-expression|the constructor}0
-Wdelete-incompletedeleting pointer to incomplete type %0 may cause undefined behavior
-Wdelete-non-virtual-dtordelete called on %0 that is abstract but has non-virtual destructor
-Wdelete-non-virtual-dtordelete called on %0 that has virtual functions but non-virtual destructor
-Wdeprecatedaccess declarations are deprecated use using declarations instead
-Wdeprecateddefinition of implicit copy %select{constructor|assignment operator}1 for %0 is deprecated because it has a user-declared %select{copy %select{assignment operator|constructor}1|destructor}2
-Wdeprecateddynamic exception specifications are deprecated
-Wdeprecated-increment-boolincrementing expression of type bool is deprecated
-Wdeprecated-objc-isa-usageassignment to Objective-C's isa is deprecated in favor of object_setClass()
-Wdeprecated-objc-isa-usagedirect access to Objective-C's isa is deprecated in favor of object_getClass()
-Wdeprecated-objc-pointer-introspectionbitmasking for introspection of Objective-C object pointers is strongly discouraged
-Wdeprecated-objc-pointer-introspection-performSelectorwarn_objc_pointer_masking.Text
-Wdeprecated-writable-stringsdummy warning to enable -fconst-strings
-Wdirect-ivar-accessinstance variable %0 is being directly accessed
-Wdistributed-object-modifiersconflicting distributed object modifiers on return type in implementation of %0
-Wdistributed-object-modifiersconflicting distributed object modifiers on parameter type in implementation of %0
-Wdivision-by-zerodivision by zero is undefined
-Wdivision-by-zeroremainder by zero is undefined
-Wdocumentationparameter '%0' not found in the function declaration
-Wdocumentationnot a Doxygen trailing comment
-Wduplicate-enumelement %0 has been implicitly assigned %1 which another element has been assigned
-Wduplicate-method-matchmultiple declarations of method %0 found and ignored
-Wdynamic-class-memaccess%select{destination for|source of|first operand of|second operand of}0 this %1 call is a pointer to dynamic class %2 vtable pointer will be %select{overwritten|copied|moved|compared}3
-Wempty-bodyswitch statement has empty body
-Wempty-bodyfor loop has empty body
-Wempty-bodyif statement has empty body
-Wempty-bodyrange-based for loop has empty body
-Wempty-bodywhile loop has empty body
-Wenum-comparecomparison of two values with different enumeration types%diff{ ($ and $)|}0,1
-Wenum-conversionimplicit conversion from enumeration type %0 to different enumeration type %1
-Wexit-time-destructorsdeclaration requires an exit-time destructor
-Wexplicit-ownership-typemethod parameter of type %0 with no explicit ownership
-Wextern-c-compat%select{|empty }0%select{struct|union}1 has size 0 in C, %select{size 1|non-zero size}2 in C++
-Wextern-initializer'extern' variable has an initializer
-Wfloat-equalcomparing floating point with == or != is unsafe
-Wformat"data argument position '%0' exceeds the number of data arguments (%1)
-Wformatposition arguments in format strings start counting at 1 (not 0)
-Wformatinvalid position specified for %select{field width|field precision}0
-Wformatcannot mix positional and non-positional arguments in format string
-Wformatvalues of type '%0' should not be used as format arguments add an explicit cast to %1 instead
-Wformatformat specifies type %0 but the argument has type %1
-Wformatzero field width in scanf format string is unused
-Wformatno closing ']' for '%%[' in scanf format string
-Wformatformat string should not be a wide string
-Wformatformat string contains '\\0' within the string body
-Wformat'%select{*|.*}0' specified field %select{width|precision}0 is missing a matching 'int' argument
-Wformatfield %select{width|precision}0 should have type %1, but argument has type %2
-Wformat%select{field width|precision}0 used with '%1' conversion specifier, resulting in undefined behavior
-Wformatformat string missing
-Wformatincomplete format specifier
-Wformatflag '%0' results in undefined behavior with '%1' conversion specifier
-Wformatflag '%0' is ignored when flag '%1' is present
-Wformatmore '%%' conversions than data arguments
-Wformatlength modifier '%0' results in undefined behavior or no effect with '%1' conversion specifier
-Wformat-extra-argsdata argument not used by format string
-Wformat-invalid-specifierinvalid conversion specifier '%0'
-Wformat-nonliteralformat string is not a string literal
-Wformat-securityformat string is not a string literal (potentially insecure)
-Wformat-zero-lengthformat string is empty
-Wgcc-compatGCC does not allow the 'cleanup' attribute argument to be anything other than a simple identifier
-Wglobal-constructorsdeclaration requires a global constructor
-Wglobal-constructorsdeclaration requires a global destructor
-Wgnu-conditional-omitted-operanduse of GNU ?: conditional expression extension, omitting middle operand
-Wheader-hygieneusing namespace directive in global context in header
-Widiomatic-parenthesesusing the result of an assignment as a condition without parentheses
-Wignored-attributes'malloc' attribute only applies to functions returning a pointer type
-Wignored-attributes%0 attribute only applies to %select{functions|unions|variables and functions|functions and methods|parameters|functions, methods and blocks|functions, methods, and classes|functions, methods, and parameters|classes|variables|methods|variables, functions and labels|fields and global variables|structs|variables, functions and tag types|thread-local variables|variables and fields|variables, data members and tag types|types and namespaces|Objective-C interfaces}1
-Wignored-attributes'%0' attribute cannot be specified on a definition
-Wignored-attributes__weak attribute cannot be specified on an automatic variable when ARC is not enabled
-Wignored-attributesObjective-C GC does not allow weak variables on the stack
-Wignored-attributes__weak attribute cannot be specified on a field declaration
-Wignored-attributesattribute %0 cannot be applied to %select{functions|Objective-C method}1 without return value
-Wignored-attributesattribute declaration must precede definition
-Wignored-attributesattribute %0 is ignored, place it after \"%select{class|struct|union|interface|enum}1\" to apply attribute to type declaration
-Wignored-attributes__declspec attribute %0 is not supported
-Wignored-attributesattribute %0 ignored, because it cannot be applied to a type
-Wignored-attributesattribute %0 after definition is ignored
-Wignored-attributes%0 attribute ignored
-Wignored-attributes'sentinel' attribute only supported for variadic %select{functions|blocks}0
-Wignored-attributes'sentinel' attribute requires named arguments
-Wignored-attributes'%0' only applies to %select{function|pointer|Objective-C object or block pointer}1 types type here is %2
-Wignored-attributes'nonnull' attribute applied to function with no pointer arguments
-Wignored-attributes%0 attribute can only be applied to instance variables or properties
-Wignored-attributesibaction attribute can only be applied to Objective-C instance methods
-Wignored-attributes%0 calling convention ignored on variadic function
-Wignored-attributes%0 only applies to variables with static storage duration and functions
-Wignored-attributes%0 attribute argument not supported: %1
-Wignored-attributes#pramga ms_struct can not be used with dynamic classes or structures
-Wignored-attributestransparent union definition must contain at least one field transparent_union attribute ignored
-Wignored-attributesfirst field of a transparent union cannot have %select{floating point|vector}0 type %1 transparent_union attribute ignored
-Wignored-attributes'gnu_inline' attribute requires function to be marked 'inline', attribute ignored
-Wignored-attributescalling convention %0 ignored for this target
-Wignored-attributestransparent_union attribute can only be applied to a union definition attribute ignored
-Wignored-attributes%select{alignment|size}0 of field %1 (%2 bits) does not match the %select{alignment|size}0 of the first field in transparent union transparent_union attribute ignored
-Wignored-attributesattribute %0 is already applied
-Wignored-attributes%0 attribute ignored for field of type %1
-Wignored-attributes%0 attribute ignored when parsing type
-Wignored-attributes%0 attribute only applies to %select{functions|methods|properties}1 that return %select{an Objective-C object|a pointer|a non-retainable pointer}2
-Wignored-attributes%0 attribute only applies to %select{Objective-C object|pointer}1 parameters
-Wignored-attributesattribute %0 is already applied with different parameters
-Wignored-attributesunknown visibility %0
-Wignored-qualifiers"'%0' type qualifier%s1 on return type %plural{1:has|:have}1 no effect
-Wignored-qualifiersARC %select{unused|__unsafe_unretained|__strong|__weak|__autoreleasing}0 lifetime qualifier on return type is ignored
-Wimplicit-atomic-propertiesproperty is assumed atomic by default
-Wimplicit-atomic-propertiesproperty is assumed atomic when auto-synthesizing the property
-Wimplicit-fallthroughfallthrough annotation in unreachable code
-Wimplicit-fallthroughunannotated fall-through between switch labels
-Wimplicit-fallthroughfallthrough annotation does not directly precede switch label
-Wimplicit-function-declarationimplicit declaration of function %0
-Wimplicit-function-declarationuse of unknown builtin %0
-Wimplicit-retain-self"block implicitly retains 'self' explicitly mention 'self' to indicate this is intended behavior
-Wincompatible-library-redeclarationincompatible redeclaration of library function %0
-Wincomplete-implementationmethod definition for %0 not found
-Winherited-variadic-ctorinheriting constructor does not inherit ellipsis
-Winitializer-overridessubobject initialization overrides initialization of other fields within its enclosing subobject
-Winitializer-overridesinitializer overrides prior initialization of this subobject
-Wint-to-pointer-castcast to %1 from smaller integer type %0
-Wint-to-void-pointer-castcast to %1 from smaller integer type %0
-Winvalid-iboutletIBOutletCollection properties should be copy/strong and not assign
-Winvalid-iboutlet%select{instance variable|property}2 with %0 attribute must be an object type (invalid %1)
-Winvalid-noreturnfunction %0 declared 'noreturn' should not return
-Winvalid-noreturnfunction declared 'noreturn' should not return
-Wlarge-by-value-copyreturn value of %0 is a large (%1 bytes) pass-by-value object pass it by reference instead ?
-Wlarge-by-value-copy%0 is a large (%1 bytes) pass-by-value argument pass it by reference instead ?
-Wliteral-conversionimplicit conversion from %0 to %1 changes value from %2 to %3
-Wliteral-rangemagnitude of floating-point constant too large for type %0 maximum is %1
-Wliteral-rangemagnitude of floating-point constant too small for type %0 minimum is %1
-Wlogical-not-parentheseslogical not is only applied to the left hand side of this comparison
-Wlogical-op-parentheses'&&' within '||'
-Wloop-analysisvariable%select{s| %1|s %1 and %2|s %1, %2, and %3|s %1, %2, %3, and %4}0 used in loop condition not modified in loop body
-Wloop-analysisvariable %0 is %select{decremented|incremented}1 both in the loop header and in the loop body
-Wmethod-signaturesconflicting parameter types in implementation of %0: %1 vs %2
-Wmethod-signaturesconflicting return type in implementation of %0: %1 vs %2
-Wmicrosoftextra qualification on member %0
-Wmismatched-method-attributesattributes on method implementation and its declaration must match
-Wmismatched-parameter-typesconflicting parameter types in implementation of %0%diff{: $ vs $|}1,2
-Wmismatched-return-typesconflicting return type in implementation of %0%diff{: $ vs $|}1,2
-Wmissing-bracessuggest braces around initialization of subobject
-Wmissing-declarations'%0' ignored on this declaration
-Wmissing-field-initializersmissing field '%0' initializer
-Wmissing-method-return-typemethod has no return type specified defaults to 'id'
-Wmissing-noreturn%select{function|method}0 %1 could be declared with attribute 'noreturn'
-Wmissing-noreturnblock could be declared with attribute 'noreturn'
-Wmissing-prototypesno previous prototype for function %0
-Wmissing-variable-declarationsno previous extern declaration for non-static variable %0
-Wmultiple-move-vbasedefaulted move assignment operator of %0 will move assign virtual base class %1 multiple times
-Wnested-anon-typesanonymous types declared in an anonymous union/struct are an extension
-Wno-typedef-redefinitionRedefinition of typedef '%0' is a C11 feature
-Wnon-literal-null-conversion"expression which evaluates to zero treated as a null pointer constant of " "type %0
-Wnon-pod-varargssecond argument to 'va_arg' is of ARC ownership-qualified type %0
-Wnon-pod-varargscannot pass %select{non-POD|non-trivial}0 object of type %1 to variadic %select{function|block|method|constructor}2 expected type from format string was %3
-Wnon-pod-varargssecond argument to 'va_arg' is of non-POD type %0
-Wnon-pod-varargscannot pass object of %select{non-POD|non-trivial}0 type %1 through variadic %select{function|block|method|constructor}2 call will abort at runtime
-Wnon-virtual-dtor%0 has virtual functions but non-virtual destructor
-Wnonnullnull passed to a callee which requires a non-null argument
-Wnull-arithmeticuse of NULL in arithmetic operation
-Wnull-arithmeticcomparison between NULL and non-pointer %select{(%1 and NULL)|(NULL and %1)}0
-Wnull-dereferenceindirection of non-volatile null pointer will be deleted, not trap
-Wobjc-autosynthesis-property-ivar-name-matchautosynthesized property %0 will use %select{|synthesized}1 instance variable %2, not existing instance variable %3
-Wobjc-forward-class-redefinitionredefinition of forward class %0 of a typedef name of an object type is ignored
-Wobjc-interface-ivarsdeclaration of instance variables in the interface is deprecated
-Wobjc-literal-comparedirect comparison of %select{an array literal|a dictionary literal|a numeric literal|a boxed expression|}0 has undefined behavior
-Wobjc-literal-missing-atsignstring literal must be prefixed by '@'
-Wobjc-method-accessinstance method %objcinstance0 not found (return type defaults to 'id') did you mean %objcinstance2?
-Wobjc-method-accessclass method %objcclass0 not found (return type defaults to 'id') did you mean %objcclass2?
-Wobjc-method-accessinstance method %objcinstance0 not found (return type defaults to 'id')
-Wobjc-method-accessinstance method %0 is being used on 'Class' which is not in the root class
-Wobjc-method-accessclass method %objcclass0 not found (return type defaults to 'id')
-Wobjc-method-accessinstance method %0 found instead of class method %1
-Wobjc-missing-property-synthesis"auto property synthesis is synthesizing property not explicitly synthesized
-Wobjc-missing-super-callsmethod possibly missing a [super %0] call
-Wobjc-noncopy-retain-block-property"retain'ed block property does not copy the block " "- use copy attribute instead
-Wobjc-nonunified-exceptionscan not catch an exception thrown with @throw in C++ in the non-unified exception model
-Wobjc-property-implementationproperty %0 requires method %1 to be defined - use @dynamic or provide a method implementation in this category
-Wobjc-property-implementationproperty %0 requires method %1 to be defined - use @synthesize, @dynamic or provide a method implementation in this class implementation
-Wobjc-property-implicit-mismatch"primary property declaration is implicitly strong while redeclaration in class extension is weak
-Wobjc-property-matches-cocoa-ownership-ruleproperty's synthesized getter follows Cocoa naming convention for returning 'owned' objects
-Wobjc-property-no-attributeno 'assign', 'retain', or 'copy' attribute is specified - 'assign' is assumed
-Wobjc-property-no-attributedefault property attribute 'assign' not appropriate for non-GC object
-Wobjc-property-synthesisauto property synthesis will not synthesize property '%0' because it is 'readwrite' but it will be synthesized 'readonly' via another property
-Wobjc-property-synthesis"auto property synthesis will not synthesize property '%0' because it cannot share an ivar with another synthesized property
-Wobjc-protocol-method-implementationcategory is implementing a method which will also be implemented by its primary class
-Wobjc-protocol-property-synthesisauto property synthesis will not synthesize property declared in a protocol
-Wobjc-redundant-literal-useusing %0 with a literal is redundant
-Wobjc-root-classclass %0 defined without specifying a base class
-Wobjc-string-comparedirect comparison of a string literal has undefined behavior
-Wobjc-string-concatenationconcatenated NSString literal for an NSArray expression - possibly missing a comma
-Wover-alignedtype %0 requires %1 bytes of alignment and the default allocator only guarantees %2 bytes
-Woverloaded-shift-op-parenthesesoverloaded operator %select{|}0 has lower precedence than comparison operator
-Woverloaded-virtual%q0 hides overloaded virtual %select{function|functions}1
-Woverriding-method-mismatchconflicting distributed object modifiers on parameter type in declaration of %0
-Woverriding-method-mismatchconflicting parameter types in declaration of %0: %1 vs %2
-Woverriding-method-mismatchconflicting variadic declaration of method and its implementation
-Woverriding-method-mismatchconflicting distributed object modifiers on return type in declaration of %0
-Woverriding-method-mismatchconflicting parameter types in declaration of %0%diff{: $ vs $|}1,2
-Woverriding-method-mismatchconflicting return type in declaration of %0%diff{: $ vs $|}1,2
-Woverriding-method-mismatchconflicting return type in declaration of %0: %1 vs %2
-Wpackedpacked attribute is unnecessary for %0
-Wpaddedpadding %select{struct|interface|class}0 %1 with %2 %select{byte|bit}3%select{|s}4 to align anonymous bit-field
-Wpaddedpadding %select{struct|interface|class}0 %1 with %2 %select{byte|bit}3%select{|s}4 to align %5
-Wpaddedpadding size of %0 with %1 %select{byte|bit}2%select{|s}3 to alignment boundary
-Wparenthesesusing the result of an assignment as a condition without parentheses
-Wparentheses%0 has lower precedence than %1 %1 will be evaluated first
-Wparenthesesoperator '?:' has lower precedence than '%0' '%0' will be evaluated first
-Wparentheses-equalityequality comparison with extraneous parentheses
-Wpointer-arithsubtraction of pointers to type %0 of zero size has undefined behavior
-Wpredefined-identifier-outside-functionpredefined identifier is only valid inside function
-Wprivate-externuse of __private_extern__ on a declaration may not produce external symbol private to the linkage unit and is deprecated
-Wprotocolmethod %0 in protocol not implemented
-Wprotocol-property-synthesis-ambiguityproperty of type %0 was selected for synthesis
-Wreadonly-iboutlet-propertyreadonly IBOutlet property '%0' when auto-synthesized may not work correctly with 'nib' loader
-Wreadonly-setter-attrsproperty attributes '%0' and '%1' are mutually exclusive
-Wreceiver-exprreceiver type %0 is not 'id' or interface pointer, consider casting it to 'id'
-Wreceiver-forward-classreceiver type %0 for instance message is a forward declaration
-Wreceiver-is-weak"weak %select{receiver|property|implicit property}0 may be unpredictably set to nil
-Wreinterpret-base-class'reinterpret_cast' %select{from|to}3 class %0 %select{to|from}3 its %select{virtual base|base at non-zero offset}2 %1 behaves differently from 'static_cast'
-Wreorder%select{field|base class}0 %1 will be initialized after %select{field|base}2 %3
-Wrequires-super-attribute%0 attribute cannot be applied to %select{methods in protocols|dealloc}1
-Wreturn-stack-addressreturning address of local temporary object
-Wreturn-stack-addressreturning address of label, which is local
-Wreturn-stack-addressaddress of stack memory associated with local variable %0 returned
-Wreturn-stack-addressreference to stack memory associated with local variable %0 returned
-Wreturn-stack-addressreturning reference to local temporary object
-Wreturn-typecontrol may reach end of non-void function
-Wreturn-typenon-void %select{function|method}1 %0 should return a value, DefaultError
-Wreturn-typecontrol reaches end of non-void function
-Wreturn-type-c-linkage%0 has C-linkage specified, but returns incomplete type %1 which could be incompatible with C
-Wreturn-type-c-linkage%0 has C-linkage specified, but returns user-defined type %1 which is incompatible with C
-Wsectionsection does not match previous declaration
-Wselectorcreating selector for nonexistent method %0
-Wselector-type-mismatchmultiple selectors named %0 found
-Wself-assignexplicitly assigning a variable of type %0 to itself
-Wself-assign-fieldassigning %select{field|instance variable}0 to itself
-Wsentinel"missing sentinel in %select{function call|method dispatch|block call}0
-Wsentinelnot enough variable arguments in %0 declaration to fit a sentinel
-Wshadowdeclaration shadows a %select{" "local variable|" "variable in %2|" "static data member of %2|" "field of %2}1
-Wshadow-ivarlocal declaration of %0 hides instance variable
-Wshift-count-negativeshift count is negative
-Wshift-count-overflowshift count = width of type
-Wshift-op-parenthesesoperator '%0' has lower precedence than '%1' '%1' will be evaluated first
-Wshift-overflowsigned shift result (%0) requires %1 bits to represent, but %2 only has %3 bits
-Wshift-sign-overflowsigned shift result (%0) sets the sign bit of the shift expression's type (%1) and becomes negative
-Wshorten-64-to-32implicit conversion loses integer precision: %0 to %1
-Wsign-comparecomparison of integers of different signs: %0 and %1
-Wsign-conversionimplicit conversion changes signedness: %0 to %1
-Wsign-conversionoperand of ? changes signedness: %0 to %1
-Wsizeof-array-argumentsizeof on array function parameter will return size of %0 instead of %1
-Wsizeof-array-decaysizeof on pointer operation will return size of %0 instead of %1
-Wsizeof-pointer-memaccess'%0' call operates on objects of type %1 while the size is based on a " "different type %2
-Wsizeof-pointer-memaccessargument to 'sizeof' in %0 call is the same pointer type %1 as the %select{destination|source}2 expected %3 or an explicit length
-Wsometimes-uninitializedvariable %0 is %select{used|captured}1 uninitialized whenever %select{'%3' condition is %select{true|false}4|'%3' loop %select{is entered|exits because its condition is false}4|'%3' loop %select{condition is true|exits because its condition is false}4|switch %3 is taken|its declaration is reached|%3 is called}2
-Wstatic-local-in-inlinenon-constant static local variable in inline function may be different in different files
-Wstatic-self-initstatic variable %0 is suspiciously used within its own initialization
-Wstrict-selector-matchmultiple methods named %0 found
-Wstring-compareresult of comparison against %select{a string literal|@encode}0 is unspecified (use strncmp instead)
-Wstring-conversionimplicit conversion turns string literal into bool: %0 to %1
-Wstring-plus-charadding %0 to a string pointer does not append to the string
-Wstring-plus-intadding %0 to a string does not append to the string
-Wstrlcpy-strlcat-sizesize argument in %0 call appears to be size of the source expected the size of the destination
-Wstrncat-sizethe value of the size argument in 'strncat' is too large, might lead to a " "buffer overflow
-Wstrncat-sizesize argument in 'strncat' call appears " "to be size of the source
-Wstrncat-sizethe value of the size argument to 'strncat' is wrong
-Wsuper-class-method-mismatchmethod parameter type %diff{$ does not match super class method parameter type $|does not match super class method parameter type}0,1
-Wswitchoverflow converting case value to switch condition type (%0 to %1)
-Wswitchcase value not in enumerated type %0
-Wswitch%0 enumeration values not handled in switch: %1, %2, %3...
-Wswitchenumeration values %0 and %1 not handled in switch
-Wswitchenumeration value %0 not handled in switch
-Wswitchenumeration values %0, %1, and %2 not handled in switch
-Wswitch-enumenumeration values %0, %1, and %2 not explicitly handled in switch
-Wswitch-enumenumeration values %0 and %1 not explicitly handled in switch
-Wswitch-enum%0 enumeration values not explicitly handled in switch: %1, %2, %3...
-Wswitch-enumenumeration value %0 not explicitly handled in switch
-Wtautological-comparecomparison of %0 unsigned%select{| enum}2 expression is always %1
-Wtautological-compare%select{self-|array }0comparison always evaluates to %select{false|true|a constant}1
-Wtautological-comparecomparison of unsigned%select{| enum}2 expression %0 is always %1
-Wtautological-constant-out-of-range-comparecomparison of constant %0 with expression of type %1 is always %select{false|true}2
-Wthread-safety-analysislocking '%0' that is already locked
-Wthread-safety-analysiscannot call function '%0' while mutex '%1' is locked
-Wthread-safety-analysis%select{reading|writing}2 the value pointed to by '%0' requires locking %select{'%1'|'%1' exclusively}2
-Wthread-safety-analysisunlocking '%0' that was not locked
-Wthread-safety-analysismutex '%0' is locked exclusively and shared in the same scope
-Wthread-safety-analysiscalling function '%0' requires %select{shared|exclusive}2 lock on '%1'
-Wthread-safety-analysis%select{reading|writing}2 variable '%0' requires locking %select{'%1'|'%1' exclusively}2
-Wthread-safety-analysiscannot resolve lock expression
-Wthread-safety-analysisexpecting mutex '%0' to be locked at the end of function
-Wthread-safety-analysismutex '%0' is not locked on every path through here
-Wthread-safety-analysis%select{reading|writing}1 the value pointed to by '%0' requires locking %select{any mutex|any mutex exclusively}1
-Wthread-safety-analysis%select{reading|writing}1 variable '%0' requires locking %select{any mutex|any mutex exclusively}1
-Wthread-safety-analysismutex '%0' is still locked at the end of function
-Wthread-safety-analysisexpecting mutex '%0' to be locked at start of each loop
-Wthread-safety-attributesignoring %0 attribute because its argument is invalid
-Wthread-safety-attributes%0 attribute only applies to %select{fields and global variables|functions and methods|classes and structs}1
-Wthread-safety-attributes%0 attribute requires arguments that are class type or point to class type type here is '%1'
-Wthread-safety-attributes%0 attribute can only be applied in a context annotated with 'lockable' attribute
-Wthread-safety-attributes%0 attribute requires arguments whose type is annotated with 'lockable' attribute type here is '%1'
-Wthread-safety-attributes'%0' only applies to pointer types type here is %1
-Wthread-safety-betaThread safety beta warning.
-Wthread-safety-precise%select{reading|writing}2 the value pointed to by '%0' requires locking %select{'%1'|'%1' exclusively}2
-Wthread-safety-precise%select{reading|writing}2 variable '%0' requires locking %select{'%1'|'%1' exclusively}2
-Wthread-safety-precisecalling function '%0' requires %select{shared|exclusive}2 lock on '%1'
-Wtype-safetythis type tag was not designed to be used with this function
-Wtype-safetyspecified %0 type tag requires a null pointer
-Wtype-safetyargument type %0 doesn't match specified '%1' type tag %select{that requires %3|}2
-Wundeclared-selectorundeclared selector %0 did you mean %1?
-Wundeclared-selectorundeclared selector %0
-Wundefined-inlineinline function %q0 is not defined
-Wundefined-internal%select{function|variable}0 %q1 has internal linkage but is not defined
-Wundefined-reinterpret-castdereference of type %1 that was reinterpret_cast from type %0 has undefined behavior
-Wundefined-reinterpret-castreinterpret_cast from %0 to %1 has undefined behavior
-Wuninitializedreference %0 is not yet bound to a value when used within its own initialization
-Wuninitializedfield %0 is uninitialized when used here
-Wuninitializedblock pointer variable %0 is uninitialized when captured by block
-Wuninitializedvariable %0 is uninitialized when used within its own initialization
-Wuninitializedvariable %0 is uninitialized when %select{used here|captured by block}1
-Wuninitializedreference %0 is not yet bound to a value when used here
-Wunneeded-internal-declaration%select{function|variable}0 %1 is not needed and will not be emitted
-Wunneeded-internal-declaration'static' function %0 declared in header file should be declared 'static inline'
-Wunneeded-member-functionmember function %0 is not needed and will not be emitted
-Wunreachable-codewill never be executed
-Wunsequencedmultiple unsequenced modifications to %0
-Wunsequencedunsequenced modification and access to %0
-Wunsupported-frienddependent nested name specifier '%0' for friend template declaration is not supported ignoring this friend declaration
-Wunsupported-frienddependent nested name specifier '%0' for friend class declaration is not supported turning off access control for %1
-Wunsupported-visibilitytarget does not support 'protected' visibility using 'default'
-Wunused-comparison%select{equality|inequality}0 comparison result unused
-Wunused-const-variableunused variable %0
-Wunused-exception-parameterunused exception parameter %0
-Wunused-functionunused function %0
-Wunused-labelunused label %0
-Wunused-member-functionunused member function %0
-Wunused-parameterunused parameter %0
-Wunused-private-fieldprivate field %0 is not used
-Wunused-property-ivarivar %0 which backs the property is not referenced in this property's accessor
-Wunused-resultignoring return value of function declared with warn_unused_result attribute
-Wunused-valueignoring return value of function declared with %0 attribute
-Wunused-valueexpression result unused should this cast be to 'void'?
-Wunused-valueexpression result unused
-Wunused-variableunused variable %0
-Wunused-volatile-lvalueexpression result unused assign into a variable to force a volatile load
-Wused-but-marked-unused%0 was marked unused but was used
-Wuser-defined-literalsuser-defined literal suffixes not starting with '_' are reserved%select{ no literal will invoke this operator|}0
-Wvarargssecond parameter of 'va_start' not last named argument
-Wvarargs'va_start' has undefined behavior with reference types
-Wvarargssecond argument to 'va_arg' is of promotable type %0 this va_arg has undefined behavior because arguments will be promoted to %1
-Wvector-conversionincompatible vector types %select{%diff{assigning to $ from $|assigning to different types}0,1|%diff{passing $ to parameter of type $|passing to parameter of different type}0,1|%diff{returning $ from a function with result type $|returning from function with different return type}0,1|%diff{converting $ to type $|converting between types}0,1|%diff{initializing $ with an expression of type $|initializing with expression of different type}0,1|%diff{sending $ to parameter of type $|sending to parameter of different type}0,1|%diff{casting $ to type $|casting between types}0,1}2
-Wvexing-parseparentheses were disambiguated as a function declaration
-Wvexing-parseempty parentheses interpreted as a function declaration
-Wvisibilitydeclaration of %0 will not be visible outside of this function
-Wvisibilityredefinition of %0 will not be visible outside of this function
-Wvlavariable length array used
-Wvla-extensionvariable length arrays are a C99 feature
-Wweak-template-vtablesexplicit template instantiation %0 will emit a vtable in every translation unit
-Wweak-vtables%0 has no out-of-line virtual method definitions; its vtable will be emitted in every translation unit

Lexer Warnings

WarningMessage
-W#pragma-messages%0
-W#warnings%0
-W#warnings%0
-Wambiguous-macroambiguous expansion of macro %0
-Wauto-importtreating #%select{include|import|include_next|__include_macros}0 as an import of module '%1'
-Wbackslash-newline-escapebackslash and newline separated by space
-Wc++11-compatidentifier after literal will be treated as a user-defined literal suffix in C++11
-Wc++11-compat'%0' is a keyword in C++11
-Wc++98-c++11-compatdigit separators are incompatible with C++ standards before C++1y
-Wc++98-c++11-compat-pedanticbinary integer literals are incompatible with C++ standards before C++1y
-Wc++98-compatraw string literals are incompatible with C++98
-Wc++98-compatunicode literals are incompatible with C++98
-Wc++98-compatuniversal character name referring to a control character is incompatible with C++98
-Wc++98-compat'::' is treated as digraph ':' (aka '[') followed by ':' in C++98
-Wc++98-compatusing this character in an identifier is incompatible with C++98
-Wc++98-compatspecifying character '%0' with a universal character name is incompatible with C++98
-Wc++98-compat-pedanticvariadic macros are incompatible with C++98
-Wc++98-compat-pedantic#line number greater than 32767 is incompatible with C++98
-Wc++98-compat-pedanticC++98 requires newline at end of file
-Wc++98-compat-pedanticempty macro arguments are incompatible with C++98
-Wc99-compatunicode literals are incompatible with C99
-Wc99-compat%select{using this character in an identifier|starting an identifier with this character}0 is incompatible with C99
-Wcomment'/*' within block comment
-Wcommentescaped newline between */ characters at block comment end
-Wdisabled-macro-expansiondisabled expansion of recursive macro
-Wheader-guard%0 is used as a header guard here, followed by #define of a different macro
-Wignored-attributesunknown attribute '%0'
-Wincomplete-moduleheader '%0' is included in module '%1' but not listed in module map
-Wincomplete-umbrellaumbrella header for module '%0' does not include header '%1'
-Winvalid-token-pastepasting formed '%0', an invalid preprocessing token, DefaultError
-Wmalformed-warning-check__has_warning expected option name (e.g. \"-Wundef\")
-Wnewline-eofno newline at end of file
-Wnull-characternull character ignored
-Wnull-characternull character(s) preserved in string literal
-Wnull-characternull character(s) preserved in character literal
-Wtrigraphsignored trigraph would end block comment
-Wtrigraphstrigraph ignored
-Wundef%0 is not defined, evaluates to 0
-Wunicodeuniversal character names are only valid in C99 or C++ treating as '\\' followed by identifier
-Wunicode\\%0 used with no following hex digits treating as '\\' followed by identifier
-Wunicodeincomplete universal character name treating as '\\' followed by identifier
-Wunicodeuniversal character name refers to a surrogate character
-Wunknown-pragmasunknown pragma ignored
-Wunknown-pragmaspragma STDC FENV_ACCESS ON is not supported, ignoring pragma
-Wunused-macrosmacro is not used

Parser Warnings

WarningMessage
-Warc-bridge-casts-disallowed-in-nonarc'%0' casts have no effect when not using ARC
-Wattributesunknown __declspec attribute %0 ignored
-Wavailability'unavailable' availability overrides all other availability information
-Wc++11-compatuse of right-shift operator ('') in template argument will require parentheses in C++11
-Wc++11-compat'auto' storage class specifier is redundant and incompatible with C++11
-Wc++98-c++11-compat'decltype(auto)' type specifier is incompatible with C++ standards before C++1y
-Wc++98-compatrange-based for loop is incompatible with C++98
-Wc++98-compatalias declarations are incompatible with C++98
-Wc++98-compatin-class initialization of non-static data members is incompatible with C++98
-Wc++98-compatdefaulted function definitions are incompatible with C++98
-Wc++98-compatrvalue references are incompatible with C++98
-Wc++98-compatreference qualifiers on functions are incompatible with C++98
-Wc++98-compatinline namespaces are incompatible with C++98
-Wc++98-compatgeneralized initializer lists are incompatible with C++98
-Wc++98-compattrailing return types are incompatible with C++98
-Wc++98-compatenumeration types with a fixed underlying type are incompatible with C++98
-Wc++98-compatalignof expressions are incompatible with C++98
-Wc++98-compat'%0' keyword is incompatible with C++98
-Wc++98-compat'decltype' type specifier is incompatible with C++98
-Wc++98-compatdeleted function definitions are incompatible with C++98
-Wc++98-compatconsecutive right angle brackets are incompatible with C++98 (use '> >')
-Wc++98-compatstatic_assert declarations are incompatible with C++98
-Wc++98-compatscoped enumerations are incompatible with C++98
-Wc++98-compatlambda expressions are incompatible with C++98
-Wc++98-compatattributes are incompatible with C++98
-Wc++98-compat'alignas' is incompatible with C++98
-Wc++98-compatnoexcept specifications are incompatible with C++98
-Wc++98-compatliteral operators are incompatible with C++98
-Wc++98-compatnoexcept expressions are incompatible with C++98
-Wc++98-compat'nullptr' is incompatible with C++98
-Wc++98-compat-pedanticextra '' outside of a function is incompatible with C++98
-Wc++98-compat-pedanticextern templates are incompatible with C++98
-Wc++98-compat-pedanticcommas at the end of enumerator lists are incompatible with C++98
-Wdangling-elseadd explicit braces to avoid dangling else
-WdeprecatedUse of 'long' with '__vector' is deprecated
-Wdeprecated-declarationsuse of C-style parameters in Objective-C method declarations is deprecated
-Wdeprecated-register'register' storage class specifier is deprecated
-Wduplicate-decl-specifierduplicate '%0' declaration specifier
-Wextra-semiextra ';' after member function definition
-Wextra-tokens"extra tokens at the end of '#pragma omp %0' are ignored
-Wgcc-compatGCC does not allow %0 attribute in this position on a function definition
-Wignored-attributesattribute %0 ignored, because it is not attached to a declaration
-Wmicrosoft-existsdependent %select{__if_not_exists|__if_exists}0 declarations are ignored
-Wmissing-selector-name%0 used as the name of the previous parameter rather than as part of the selector
-Wsemicolon-before-method-bodysemicolon before method body is ignored
-Wsource-uses-openmp"unexpected '#pragma omp ...' in program
-Wstatic-inline-explicit-instantiationignoring '%select{static|inline}0' keyword on explicit template instantiation


服务器 #define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <iphlpapi.h> #include <windows.h> #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "iphlpapi.lib") #define BUFFER_SIZE 1024 #define MAX_DATA_SIZE 120 #define DEBUG_MODE 1 // 启用调试输出 SOCKET rawSocket; unsigned short processId; BOOL isRunning = TRUE; #define SIO_RCVALL _WSAIOW(IOC_VENDOR, 1) #define RCVALL_ON 1 typedef struct { unsigned char ip_hl : 4; unsigned char ip_v : 4; unsigned char ip_tos; unsigned short ip_len; unsigned short ip_id; unsigned short ip_off; unsigned char ip_ttl; unsigned char ip_p; unsigned short ip_sum; struct in_addr ip_src; struct in_addr ip_dst; } IP_HEADER; typedef struct { unsigned char type; unsigned char code; unsigned short checksum; unsigned short id; unsigned short seq; char data[128]; } ICMP_HEADER; typedef struct { unsigned short fragment_index; unsigned short fragment_count; char data[MAX_DATA_SIZE]; } CMD_FRAGMENT; // 计算校验和 unsigned short checksum(unsigned short* buf, int len) { unsigned long sum = 0; while (len > 1) { sum += *buf++; len -= 2; } if (len == 1) { sum += (unsigned char)*buf; } sum = (sum >> 16) + (sum & 0xffff); sum += sum >> 16; return (unsigned short)~sum; } // 获取本地IP地址列表 void printLocalIPs() { PIP_ADAPTER_INFO pAdapterInfo; PIP_ADAPTER_INFO pAdapter = NULL; DWORD dwRetVal = 0; ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO); pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen); if (!pAdapterInfo) return; if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW) { free(pAdapterInfo); pAdapterInfo = (IP_ADAPTER_INFO*)malloc(ulOutBufLen); if (!pAdapterInfo) return; } if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == NO_ERROR) { pAdapter = pAdapterInfo; printf("可用的本地IP地址:\n"); while (pAdapter) { if (pAdapter->IpAddressList.IpAddress.String[0] != '0') { printf(" - %s (接口: %s)\n", pAdapter->IpAddressList.IpAddress.String, pAdapter->Description); } pAdapter = pAdapter->Next; } } free(pAdapterInfo); } // 发送ICMP消息 int sendICMPMessage(const char* ipAddress, const char* message, int seq, int type) { struct sockaddr_in destAddr; char sendBuf[sizeof(ICMP_HEADER) + 128] = { 0 }; ICMP_HEADER* icmpHeader = (ICMP_HEADER*)sendBuf; int ret; memset(&destAddr, 0, sizeof(destAddr)); destAddr.sin_family = AF_INET; if (inet_pton(AF_INET, ipAddress, &destAddr.sin_addr) != 1) { printf("❌ 无效的IP地址: %s\n", ipAddress); return -1; } icmpHeader->type = type; icmpHeader->code = 0; icmpHeader->id = processId; icmpHeader->seq = htons(seq); strncpy(icmpHeader->data, message, sizeof(icmpHeader->data) - 1); icmpHeader->data[sizeof(icmpHeader->data) - 1] = '\0'; int icmpTotalLen = offsetof(ICMP_HEADER, data) + strlen(icmpHeader->data) + 1; icmpHeader->checksum = 0; icmpHeader->checksum = checksum((unsigned short*)icmpHeader, icmpTotalLen); ret = sendto(rawSocket, sendBuf, icmpTotalLen, 0, (struct sockaddr*)&destAddr, sizeof(destAddr)); if (ret == SOCKET_ERROR) { printf("❌ 发送失败 (错误码: %d)\n", WSAGetLastError()); } return ret; } // 发送命令执行结果 void sendCommandResult(const char* ipAddress, const char* result, int seq) { int totalLength = strlen(result); int fragmentCount = (totalLength + MAX_DATA_SIZE - 1) / MAX_DATA_SIZE; int currentSeq = seq; printf("命令结果大小: %d字节, 分%d个包发送\n", totalLength, fragmentCount); for (int i = 0; i < fragmentCount; i++) { char fragmentBuffer[sizeof(CMD_FRAGMENT)] = { 0 }; CMD_FRAGMENT* fragment = (CMD_FRAGMENT*)fragmentBuffer; fragment->fragment_index = htons(i); fragment->fragment_count = htons(fragmentCount); int copySize = (i == fragmentCount - 1) ? (totalLength - i * MAX_DATA_SIZE) : MAX_DATA_SIZE; memcpy(fragment->data, result + i * MAX_DATA_SIZE, copySize); sendICMPMessage(ipAddress, fragmentBuffer, currentSeq, 0); #if DEBUG_MODE printf("✅ 发送分片 %d/%d (序列号: %d, 大小: %d字节)\n", i + 1, fragmentCount, currentSeq, copySize); #endif currentSeq++; Sleep(30); } sendICMPMessage(ipAddress, "CMD_FINISH", currentSeq, 0); printf("✅ 命令结果发送完成\n"); } // 执行命令 char* execute_command(const char* cmd) { FILE* fp = _popen(cmd, "r"); if (!fp) return _strdup("命令执行失败"); char buffer[BUFFER_SIZE]; size_t totalSize = 0; size_t allocated = BUFFER_SIZE * 10; char* result = (char*)malloc(allocated); if (!result) { _pclose(fp); return _strdup("内存分配失败"); } result[0] = '\0'; while (fgets(buffer, sizeof(buffer), fp)) { size_t len = strlen(buffer); if (totalSize + len + 1 > allocated) { allocated *= 2; char* newResult = (char*)realloc(result, allocated); if (!newResult) { free(result); _pclose(fp); return _strdup("内存分配失败"); } result = newResult; } strcat(result, buffer); totalSize += len; } _pclose(fp); return result; } // 处理命令 void processCommand(const char* srcIP, const char* command) { printf("\n📩 收到命令: %s\n", command); // 保存客户端IP到全局变量 static char clientIP[INET_ADDRSTRLEN]; strncpy(clientIP, srcIP, INET_ADDRSTRLEN); char* result = execute_command(command); if (!result) result = _strdup("命令执行失败"); sendCommandResult(srcIP, result, 1); free(result); } // 主循环 void serverLoop() { char recvBuf[65535]; struct sockaddr_in srcAddr; int srcAddrSize = sizeof(srcAddr); printf("服务器已启动,等待命令...\n"); while (isRunning) { int ret = recvfrom(rawSocket, recvBuf, sizeof(recvBuf), 0, (struct sockaddr*)&srcAddr, &srcAddrSize); if (ret == SOCKET_ERROR) { int error = WSAGetLastError(); if (error == WSAETIMEDOUT) continue; printf("❌ 接收错误: %d\n", error); continue; } IP_HEADER* ipHeader = (IP_HEADER*)recvBuf; if (ipHeader->ip_p != IPPROTO_ICMP) continue; int ipHeaderLen = ipHeader->ip_hl * 4; if (ipHeaderLen < sizeof(IP_HEADER)) continue; ICMP_HEADER* icmpHeader = (ICMP_HEADER*)(recvBuf + ipHeaderLen); char ipStr[INET_ADDRSTRLEN]; InetNtopA(AF_INET, &ipHeader->ip_src, ipStr, INET_ADDRSTRLEN); #if DEBUG_MODE printf("\n收到 %d 字节数据,来源: %s\n", ret, ipStr); printf("IP协议: %d, ICMP类型: %d\n", ipHeader->ip_p, icmpHeader->type); printf("数据头: %.4s\n", icmpHeader->data); #endif if (icmpHeader->type == 8 && strncmp(icmpHeader->data, "cmd:", 4) == 0) { processCommand(ipStr, icmpHeader->data + 4); } } } int main() { WSADATA wsaData; struct sockaddr_in localAddr; DWORD bytesReturned; char ipChoice[16]; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("❌ WSAStartup失败: %d\n", WSAGetLastError()); return 1; } printLocalIPs(); processId = (unsigned short)GetCurrentProcessId(); printf("\n服务器进程ID: %d\n", processId); printf("\n请输入要绑定的IP地址: "); if (fgets(ipChoice, sizeof(ipChoice), stdin) == NULL) { printf("❌ 输入错误\n"); WSACleanup(); return 1; } ipChoice[strcspn(ipChoice, "\n")] = '\0'; rawSocket = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, WSA_FLAG_OVERLAPPED); if (rawSocket == INVALID_SOCKET) { printf("❌ 创建套接字失败: %d (需管理员权限)\n", WSAGetLastError()); WSACleanup(); return 1; } memset(&localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET; localAddr.sin_addr.s_addr = inet_addr(ipChoice); if (bind(rawSocket, (struct sockaddr*)&localAddr, sizeof(localAddr)) == SOCKET_ERROR) { printf("❌ 绑定失败: %d\n", WSAGetLastError()); closesocket(rawSocket); WSACleanup(); return 1; } printf("✅ 已绑定到: %s\n", ipChoice); unsigned long optval = RCVALL_ON; if (WSAIoctl(rawSocket, SIO_RCVALL, &optval, sizeof(optval), NULL, 0, &bytesReturned, NULL, NULL) == SOCKET_ERROR) { printf("⚠️ 警告: 混杂模式未启用 (错误码: %d)\n", WSAGetLastError()); printf("➡️ 仍可接收定向到本机的消息\n"); } else { printf("✅ 已启用混杂模式\n"); } serverLoop(); printf("\n关闭服务器...\n"); closesocket(rawSocket); WSACleanup(); return 0; } 客户端 #define _WINSOCK_DEPRECATED_NO_WARNINGS #define _CRT_SECURE_NO_WARNINGS #include <winsock2.h> #include <ws2tcpip.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #pragma comment(lib, "ws2_32.lib") #define DEBUG_MODE 1 #define MAX_PACKET_SIZE 1024 #define ICMP_ECHO_REQUEST 8 #define ICMP_ECHO_REPLY 0 #define ICMP_MIN_SIZE 8 #define CMD_PREFIX "cmd:" #define CMD_PREFIX_LEN 4 #define CMD_FRAGMENT_PREFIX "CMD_" #define CMD_FRAGMENT_PREFIX_LEN 4 // 强制1字节对齐确保跨平台兼容性 #pragma pack(push, 1) typedef struct { unsigned char ip_hl : 4; unsigned char ip_v : 4; unsigned char ip_tos; unsigned short ip_len; unsigned short ip_id; unsigned short ip_off; unsigned char ip_ttl; unsigned char ip_p; unsigned short ip_sum; unsigned int ip_src; unsigned int ip_dst; } IP_HEADER; typedef struct { unsigned char icmp_type; unsigned char icmp_code; unsigned short icmp_checksum; unsigned short icmp_id; unsigned short icmp_seq; } ICMP_HEADER; typedef struct { char prefix[4]; // "CMD_" unsigned short total_size; unsigned short fragment_count; unsigned short fragment_index; char data[1]; // 可变长度数据 } CMD_FRAGMENT; #pragma pack(pop) // 计算校验和函数 unsigned short checksum(unsigned short* buffer, int size) { unsigned long cksum = 0; while (size > 1) { cksum += *buffer++; size -= sizeof(unsigned short); } if (size) { cksum += *(unsigned char*)buffer; } cksum = (cksum >> 16) + (cksum & 0xffff); cksum += (cksum >> 16); return (unsigned short)(~cksum); } // 发送命令函数 void sendCommand(const char* command, const char* srcIP, const char* dstIP, int seq) { SOCKET rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (rawSocket == INVALID_SOCKET) { printf("创建原始套接字失败: %d\n", WSAGetLastError()); return; } // 设置源IP地址 sockaddr_in srcAddr; memset(&srcAddr, 0, sizeof(srcAddr)); srcAddr.sin_family = AF_INET; srcAddr.sin_addr.s_addr = inet_addr(srcIP); if (bind(rawSocket, (sockaddr*)&srcAddr, sizeof(srcAddr)) == SOCKET_ERROR) { printf("绑定到源IP %s 失败: %d\n", srcIP, WSAGetLastError()); closesocket(rawSocket); return; } printf("? 已绑定到源IP: %s\n", srcIP); // 设置目标地址 sockaddr_in dstAddr; memset(&dstAddr, 0, sizeof(dstAddr)); dstAddr.sin_family = AF_INET; dstAddr.sin_addr.s_addr = inet_addr(dstIP); // 构造ICMP请求包 char sendBuf[MAX_PACKET_SIZE] = { 0 }; ICMP_HEADER* icmpHeader = (ICMP_HEADER*)sendBuf; icmpHeader->icmp_type = ICMP_ECHO_REQUEST; icmpHeader->icmp_code = 0; icmpHeader->icmp_id = (unsigned short)GetCurrentProcessId(); icmpHeader->icmp_seq = htons(seq); // 添加命令前缀和内容 char* payload = sendBuf + sizeof(ICMP_HEADER); strncpy(payload, CMD_PREFIX, CMD_PREFIX_LEN); strncpy(payload + CMD_PREFIX_LEN, command, MAX_PACKET_SIZE - sizeof(ICMP_HEADER) - CMD_PREFIX_LEN); int payloadLen = CMD_PREFIX_LEN + (int)strlen(command) + 1; int packetSize = sizeof(ICMP_HEADER) + payloadLen; // 计算校验和 icmpHeader->icmp_checksum = 0; icmpHeader->icmp_checksum = checksum((unsigned short*)icmpHeader, packetSize); // 发送命令 if (sendto(rawSocket, sendBuf, packetSize, 0, (sockaddr*)&dstAddr, sizeof(dstAddr)) == SOCKET_ERROR) { printf("发送命令失败: %d\n", WSAGetLastError()); } else { printf("? 发送命令: %s (大小: %d字节, 序列号: %d)\n", command, packetSize, seq); } closesocket(rawSocket); } // 接收命令结果函数 void receiveCommandResult(int seq, const char* srcIP) { SOCKET rawSocket = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP); if (rawSocket == INVALID_SOCKET) { printf("创建原始套接字失败: %d\n", WSAGetLastError()); return; } // 设置接收超时 DWORD timeout = 5000; setsockopt(rawSocket, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout)); // 设置源IP地址(仅用于接收) sockaddr_in localAddr; memset(&localAddr, 0, sizeof(localAddr)); localAddr.sin_family = AF_INET; localAddr.sin_addr.s_addr = inet_addr(srcIP); bind(rawSocket, (sockaddr*)&localAddr, sizeof(localAddr)); printf("等待结果 (超时: %dms)...\n", timeout); char recvBuf[MAX_PACKET_SIZE] = { 0 }; char* resultBuffer = NULL; int resultSize = 0; int fragmentCount = 0; int receivedFragments = 0; time_t startTime = time(NULL); while (1) { // 检查超时 if (time(NULL) - startTime > 5) { printf("? 接收超时\n"); break; } sockaddr_in fromAddr; int fromAddrLen = sizeof(fromAddr); int bytesRead = recvfrom(rawSocket, recvBuf, sizeof(recvBuf), 0, (sockaddr*)&fromAddr, &fromAddrLen); if (bytesRead == SOCKET_ERROR) { if (WSAGetLastError() == WSAETIMEDOUT) { printf("? 接收超时\n"); break; } printf("接收错误: %d\n", WSAGetLastError()); continue; } // 解析IP头 IP_HEADER* ipHeader = (IP_HEADER*)recvBuf; int ipHeaderLen = ipHeader->ip_hl * 4; // 检查协议类型 if (ipHeader->ip_p != IPPROTO_ICMP) { continue; } // 解析ICMP头 ICMP_HEADER* icmpHeader = (ICMP_HEADER*)(recvBuf + ipHeaderLen); unsigned short recvSeq = ntohs(icmpHeader->icmp_seq); // 调试输出:显示接收到的包信息 #if DEBUG_MODE char fromIP[16]; strcpy(fromIP, inet_ntoa(fromAddr.sin_addr)); printf("收到包: 类型=%d, 序列号=%d, 来源IP=%s\n", icmpHeader->icmp_type, recvSeq, fromIP); #endif // 只处理当前序列号范围内的包 if (recvSeq < seq) { #if DEBUG_MODE printf("跳过过时包 (seq=%d < 当前=%d)\n", recvSeq, seq); #endif continue; } // 处理ICMP响应 if (icmpHeader->icmp_type == ICMP_ECHO_REPLY) { char* payload = recvBuf + ipHeaderLen + sizeof(ICMP_HEADER); int payloadLen = bytesRead - ipHeaderLen - sizeof(ICMP_HEADER); // 检查是否是命令分片 if (payloadLen > CMD_FRAGMENT_PREFIX_LEN && memcmp(payload, CMD_FRAGMENT_PREFIX, CMD_FRAGMENT_PREFIX_LEN) == 0) { CMD_FRAGMENT* fragment = (CMD_FRAGMENT*)payload; // 关键修复:正确转换网络字节序 unsigned short fragIndex = ntohs(fragment->fragment_index); unsigned short fragCount = ntohs(fragment->fragment_count); unsigned short totalSize = ntohs(fragment->total_size); // 首次收到分片时初始化缓冲区 if (fragmentCount == 0) { // 添加合理性检查 if (fragCount > 1000 || totalSize > 10 * 1024 * 1024) { printf("! 无效的分片参数: count=%d, size=%d\n", fragCount, totalSize); continue; } fragmentCount = fragCount; resultSize = totalSize; resultBuffer = (char*)malloc(resultSize + 1); // +1 for null terminator if (!resultBuffer) { printf("内存分配失败\n"); break; } memset(resultBuffer, 0, resultSize + 1); printf("? 命令结果大小: %d字节, 分%d个包发送\n", resultSize, fragmentCount); } // 添加分片索引有效性检查 if (fragIndex < fragmentCount) { // 计算数据长度 size_t headerSize = offsetof(CMD_FRAGMENT, data); int fragDataLen = payloadLen - headerSize; // 防止负长度 if (fragDataLen < 0) fragDataLen = 0; // 复制数据到结果缓冲区 int maxFragmentSize = MAX_PACKET_SIZE - sizeof(ICMP_HEADER) - headerSize; int offset = fragIndex * maxFragmentSize; if (offset + fragDataLen <= resultSize) { memcpy(resultBuffer + offset, fragment->data, fragDataLen); } else if (offset < resultSize) { // 处理最后一个分片 int remaining = resultSize - offset; memcpy(resultBuffer + offset, fragment->data, remaining); fragDataLen = remaining; // 更新实际复制长度 } receivedFragments++; #if DEBUG_MODE printf("? 收到分片 %d/%d (序列号: %d, 大小: %d字节)\n", fragIndex + 1, fragmentCount, recvSeq, fragDataLen); #endif // 检查是否收到所有分片 if (receivedFragments >= fragmentCount) { printf("? 命令结果接收完成\n"); printf("命令结果:\n%.*s\n", resultSize, resultBuffer); free(resultBuffer); closesocket(rawSocket); return; } } else { #if DEBUG_MODE printf("! 无效分片索引: %d (最大: %d)\n", fragIndex, fragmentCount); #endif } } } } if (resultBuffer) { free(resultBuffer); } closesocket(rawSocket); printf("? 未收到有效结果\n"); } // 主函数 int main() { WSADATA wsaData; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { printf("WSAStartup失败: %d\n", WSAGetLastError()); return 1; } printf("客户端\n"); // 获取本地IP地址 char hostname[256]; if (gethostname(hostname, sizeof(hostname))) { printf("获取主机名失败\n"); return 1; } struct hostent* host = gethostbyname(hostname); if (!host) { printf("获取IP地址失败\n"); return 1; } printf("可用的本地IP地址:\n"); for (int i = 0; host->h_addr_list[i]; i++) { struct in_addr addr; memcpy(&addr, host->h_addr_list[i], sizeof(struct in_addr)); printf(" - %s\n", inet_ntoa(addr)); } printf("客户端进程ID: %d\n\n", GetCurrentProcessId()); char serverIP[16] = { 0 }; char clientIP[16] = { 0 }; printf("服务器IP地址: "); scanf("%15s", serverIP); printf("客户端使用的源IP地址: "); scanf("%15s", clientIP); int seq = 1; char command[256] = { 0 }; while (1) { printf("\n输入命令 (exit退出): "); scanf(" %255[^\n]", command); // 限制输入长度防止溢出 if (strcmp(command, "exit") == 0) { break; } sendCommand(command, clientIP, serverIP, seq); receiveCommandResult(seq, clientIP); seq++; } WSACleanup(); return 0; }
最新发布
08-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值